Merge branch 'release-0.7'
[Sone.git] / src / main / java / net / pterodactylus / sone / core / Core.java
1 /*
2  * Sone - Core.java - Copyright © 2010 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sone.core;
19
20 import java.net.MalformedURLException;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Set;
28 import java.util.Map.Entry;
29 import java.util.concurrent.ExecutorService;
30 import java.util.concurrent.Executors;
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.data.Album;
38 import net.pterodactylus.sone.data.Client;
39 import net.pterodactylus.sone.data.Image;
40 import net.pterodactylus.sone.data.Post;
41 import net.pterodactylus.sone.data.Profile;
42 import net.pterodactylus.sone.data.Reply;
43 import net.pterodactylus.sone.data.Sone;
44 import net.pterodactylus.sone.data.TemporaryImage;
45 import net.pterodactylus.sone.data.Profile.Field;
46 import net.pterodactylus.sone.fcp.FcpInterface;
47 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
48 import net.pterodactylus.sone.freenet.wot.Identity;
49 import net.pterodactylus.sone.freenet.wot.IdentityListener;
50 import net.pterodactylus.sone.freenet.wot.IdentityManager;
51 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
52 import net.pterodactylus.sone.freenet.wot.Trust;
53 import net.pterodactylus.sone.freenet.wot.WebOfTrustException;
54 import net.pterodactylus.sone.main.SonePlugin;
55 import net.pterodactylus.util.config.Configuration;
56 import net.pterodactylus.util.config.ConfigurationException;
57 import net.pterodactylus.util.logging.Logging;
58 import net.pterodactylus.util.number.Numbers;
59 import net.pterodactylus.util.service.AbstractService;
60 import net.pterodactylus.util.thread.Ticker;
61 import net.pterodactylus.util.validation.EqualityValidator;
62 import net.pterodactylus.util.validation.IntegerRangeValidator;
63 import net.pterodactylus.util.validation.OrValidator;
64 import net.pterodactylus.util.validation.Validation;
65 import net.pterodactylus.util.version.Version;
66 import freenet.keys.FreenetURI;
67
68 /**
69  * The Sone core.
70  *
71  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
72  */
73 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
74
75         /**
76          * Enumeration for the possible states of a {@link Sone}.
77          *
78          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
79          */
80         public enum SoneStatus {
81
82                 /** The Sone is unknown, i.e. not yet downloaded. */
83                 unknown,
84
85                 /** The Sone is idle, i.e. not being downloaded or inserted. */
86                 idle,
87
88                 /** The Sone is currently being inserted. */
89                 inserting,
90
91                 /** The Sone is currently being downloaded. */
92                 downloading,
93         }
94
95         /** The logger. */
96         private static final Logger logger = Logging.getLogger(Core.class);
97
98         /** The options. */
99         private final Options options = new Options();
100
101         /** The preferences. */
102         private final Preferences preferences = new Preferences(options);
103
104         /** The core listener manager. */
105         private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
106
107         /** The configuration. */
108         private Configuration configuration;
109
110         /** Whether we’re currently saving the configuration. */
111         private boolean storingConfiguration = false;
112
113         /** The identity manager. */
114         private final IdentityManager identityManager;
115
116         /** Interface to freenet. */
117         private final FreenetInterface freenetInterface;
118
119         /** The Sone downloader. */
120         private final SoneDownloader soneDownloader;
121
122         /** The image inserter. */
123         private final ImageInserter imageInserter;
124
125         /** Sone downloader thread-pool. */
126         private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10);
127
128         /** The update checker. */
129         private final UpdateChecker updateChecker;
130
131         /** The FCP interface. */
132         private volatile FcpInterface fcpInterface;
133
134         /** The Sones’ statuses. */
135         /* synchronize access on itself. */
136         private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
137
138         /** Locked local Sones. */
139         /* synchronize on itself. */
140         private final Set<Sone> lockedSones = new HashSet<Sone>();
141
142         /** Sone inserters. */
143         /* synchronize access on this on localSones. */
144         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
145
146         /** Sone rescuers. */
147         /* synchronize access on this on localSones. */
148         private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
149
150         /** All local Sones. */
151         /* synchronize access on this on itself. */
152         private Map<String, Sone> localSones = new HashMap<String, Sone>();
153
154         /** All remote Sones. */
155         /* synchronize access on this on itself. */
156         private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
157
158         /** All new Sones. */
159         private Set<String> newSones = new HashSet<String>();
160
161         /** All known Sones. */
162         /* synchronize access on {@link #newSones}. */
163         private Set<String> knownSones = new HashSet<String>();
164
165         /** All posts. */
166         private Map<String, Post> posts = new HashMap<String, Post>();
167
168         /** All new posts. */
169         private Set<String> newPosts = new HashSet<String>();
170
171         /** All known posts. */
172         /* synchronize access on {@link #newPosts}. */
173         private Set<String> knownPosts = new HashSet<String>();
174
175         /** All replies. */
176         private Map<String, Reply> replies = new HashMap<String, Reply>();
177
178         /** All new replies. */
179         private Set<String> newReplies = new HashSet<String>();
180
181         /** All known replies. */
182         private Set<String> knownReplies = new HashSet<String>();
183
184         /** All bookmarked posts. */
185         /* synchronize access on itself. */
186         private Set<String> bookmarkedPosts = new HashSet<String>();
187
188         /** Trusted identities, sorted by own identities. */
189         private Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
190
191         /** All known albums. */
192         private Map<String, Album> albums = new HashMap<String, Album>();
193
194         /** All known images. */
195         private Map<String, Image> images = new HashMap<String, Image>();
196
197         /** All temporary images. */
198         private Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
199
200         /** Ticker for threads that mark own elements as known. */
201         private Ticker localElementTicker = new Ticker();
202
203         /** The time the configuration was last touched. */
204         private volatile long lastConfigurationUpdate;
205
206         /**
207          * Creates a new core.
208          *
209          * @param configuration
210          *            The configuration of the core
211          * @param freenetInterface
212          *            The freenet interface
213          * @param identityManager
214          *            The identity manager
215          */
216         public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
217                 super("Sone Core");
218                 this.configuration = configuration;
219                 this.freenetInterface = freenetInterface;
220                 this.identityManager = identityManager;
221                 this.soneDownloader = new SoneDownloader(this, freenetInterface);
222                 this.imageInserter = new ImageInserter(this, freenetInterface);
223                 this.updateChecker = new UpdateChecker(freenetInterface);
224         }
225
226         //
227         // LISTENER MANAGEMENT
228         //
229
230         /**
231          * Adds a new core listener.
232          *
233          * @param coreListener
234          *            The listener to add
235          */
236         public void addCoreListener(CoreListener coreListener) {
237                 coreListenerManager.addListener(coreListener);
238         }
239
240         /**
241          * Removes a core listener.
242          *
243          * @param coreListener
244          *            The listener to remove
245          */
246         public void removeCoreListener(CoreListener coreListener) {
247                 coreListenerManager.removeListener(coreListener);
248         }
249
250         //
251         // ACCESSORS
252         //
253
254         /**
255          * Sets the configuration to use. This will automatically save the current
256          * configuration to the given configuration.
257          *
258          * @param configuration
259          *            The new configuration to use
260          */
261         public void setConfiguration(Configuration configuration) {
262                 this.configuration = configuration;
263                 touchConfiguration();
264         }
265
266         /**
267          * Returns the options used by the core.
268          *
269          * @return The options of the core
270          */
271         public Preferences getPreferences() {
272                 return preferences;
273         }
274
275         /**
276          * Returns the identity manager used by the core.
277          *
278          * @return The identity manager
279          */
280         public IdentityManager getIdentityManager() {
281                 return identityManager;
282         }
283
284         /**
285          * Returns the update checker.
286          *
287          * @return The update checker
288          */
289         public UpdateChecker getUpdateChecker() {
290                 return updateChecker;
291         }
292
293         /**
294          * Sets the FCP interface to use.
295          *
296          * @param fcpInterface
297          *            The FCP interface to use
298          */
299         public void setFcpInterface(FcpInterface fcpInterface) {
300                 this.fcpInterface = fcpInterface;
301         }
302
303         /**
304          * Returns the status of the given Sone.
305          *
306          * @param sone
307          *            The Sone to get the status for
308          * @return The status of the Sone
309          */
310         public SoneStatus getSoneStatus(Sone sone) {
311                 synchronized (soneStatuses) {
312                         return soneStatuses.get(sone);
313                 }
314         }
315
316         /**
317          * Sets the status of the given Sone.
318          *
319          * @param sone
320          *            The Sone to set the status of
321          * @param soneStatus
322          *            The status to set
323          */
324         public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
325                 synchronized (soneStatuses) {
326                         soneStatuses.put(sone, soneStatus);
327                 }
328         }
329
330         /**
331          * Returns the Sone rescuer for the given local Sone.
332          *
333          * @param sone
334          *            The local Sone to get the rescuer for
335          * @return The Sone rescuer for the given Sone
336          */
337         public SoneRescuer getSoneRescuer(Sone sone) {
338                 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", isLocalSone(sone)).check();
339                 synchronized (localSones) {
340                         SoneRescuer soneRescuer = soneRescuers.get(sone);
341                         if (soneRescuer == null) {
342                                 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
343                                 soneRescuers.put(sone, soneRescuer);
344                                 soneRescuer.start();
345                         }
346                         return soneRescuer;
347                 }
348         }
349
350         /**
351          * Returns whether the given Sone is currently locked.
352          *
353          * @param sone
354          *            The sone to check
355          * @return {@code true} if the Sone is locked, {@code false} if it is not
356          */
357         public boolean isLocked(Sone sone) {
358                 synchronized (lockedSones) {
359                         return lockedSones.contains(sone);
360                 }
361         }
362
363         /**
364          * Returns all Sones, remote and local.
365          *
366          * @return All Sones
367          */
368         public Set<Sone> getSones() {
369                 Set<Sone> allSones = new HashSet<Sone>();
370                 allSones.addAll(getLocalSones());
371                 allSones.addAll(getRemoteSones());
372                 return allSones;
373         }
374
375         /**
376          * Returns the Sone with the given ID, regardless whether it’s local or
377          * remote.
378          *
379          * @param id
380          *            The ID of the Sone to get
381          * @return The Sone with the given ID, or {@code null} if there is no such
382          *         Sone
383          */
384         public Sone getSone(String id) {
385                 return getSone(id, true);
386         }
387
388         /**
389          * Returns the Sone with the given ID, regardless whether it’s local or
390          * remote.
391          *
392          * @param id
393          *            The ID of the Sone to get
394          * @param create
395          *            {@code true} to create a new Sone if none exists,
396          *            {@code false} to return {@code null} if a Sone with the given
397          *            ID does not exist
398          * @return The Sone with the given ID, or {@code null} if there is no such
399          *         Sone
400          */
401         @Override
402         public Sone getSone(String id, boolean create) {
403                 if (isLocalSone(id)) {
404                         return getLocalSone(id);
405                 }
406                 return getRemoteSone(id, create);
407         }
408
409         /**
410          * Checks whether the core knows a Sone with the given ID.
411          *
412          * @param id
413          *            The ID of the Sone
414          * @return {@code true} if there is a Sone with the given ID, {@code false}
415          *         otherwise
416          */
417         public boolean hasSone(String id) {
418                 return isLocalSone(id) || isRemoteSone(id);
419         }
420
421         /**
422          * Returns whether the given Sone is a local Sone.
423          *
424          * @param sone
425          *            The Sone to check for its locality
426          * @return {@code true} if the given Sone is local, {@code false} otherwise
427          */
428         public boolean isLocalSone(Sone sone) {
429                 synchronized (localSones) {
430                         return localSones.containsKey(sone.getId());
431                 }
432         }
433
434         /**
435          * Returns whether the given ID is the ID of a local Sone.
436          *
437          * @param id
438          *            The Sone ID to check for its locality
439          * @return {@code true} if the given ID is a local Sone, {@code false}
440          *         otherwise
441          */
442         public boolean isLocalSone(String id) {
443                 synchronized (localSones) {
444                         return localSones.containsKey(id);
445                 }
446         }
447
448         /**
449          * Returns all local Sones.
450          *
451          * @return All local Sones
452          */
453         public Set<Sone> getLocalSones() {
454                 synchronized (localSones) {
455                         return new HashSet<Sone>(localSones.values());
456                 }
457         }
458
459         /**
460          * Returns the local Sone with the given ID.
461          *
462          * @param id
463          *            The ID of the Sone to get
464          * @return The Sone with the given ID
465          */
466         public Sone getLocalSone(String id) {
467                 return getLocalSone(id, true);
468         }
469
470         /**
471          * Returns the local Sone with the given ID, optionally creating a new Sone.
472          *
473          * @param id
474          *            The ID of the Sone
475          * @param create
476          *            {@code true} to create a new Sone if none exists,
477          *            {@code false} to return null if none exists
478          * @return The Sone with the given ID, or {@code null}
479          */
480         public Sone getLocalSone(String id, boolean create) {
481                 synchronized (localSones) {
482                         Sone sone = localSones.get(id);
483                         if ((sone == null) && create) {
484                                 sone = new Sone(id);
485                                 localSones.put(id, sone);
486                                 setSoneStatus(sone, SoneStatus.unknown);
487                         }
488                         return sone;
489                 }
490         }
491
492         /**
493          * Returns all remote Sones.
494          *
495          * @return All remote Sones
496          */
497         public Set<Sone> getRemoteSones() {
498                 synchronized (remoteSones) {
499                         return new HashSet<Sone>(remoteSones.values());
500                 }
501         }
502
503         /**
504          * Returns the remote Sone with the given ID.
505          *
506          * @param id
507          *            The ID of the remote Sone to get
508          * @return The Sone with the given ID
509          */
510         public Sone getRemoteSone(String id) {
511                 return getRemoteSone(id, true);
512         }
513
514         /**
515          * Returns the remote Sone with the given ID.
516          *
517          * @param id
518          *            The ID of the remote Sone to get
519          * @param create
520          *            {@code true} to always create a Sone, {@code false} to return
521          *            {@code null} if no Sone with the given ID exists
522          * @return The Sone with the given ID
523          */
524         public Sone getRemoteSone(String id, boolean create) {
525                 synchronized (remoteSones) {
526                         Sone sone = remoteSones.get(id);
527                         if ((sone == null) && create) {
528                                 sone = new Sone(id);
529                                 remoteSones.put(id, sone);
530                                 setSoneStatus(sone, SoneStatus.unknown);
531                         }
532                         return sone;
533                 }
534         }
535
536         /**
537          * Returns whether the given Sone is a remote Sone.
538          *
539          * @param sone
540          *            The Sone to check
541          * @return {@code true} if the given Sone is a remote Sone, {@code false}
542          *         otherwise
543          */
544         public boolean isRemoteSone(Sone sone) {
545                 synchronized (remoteSones) {
546                         return remoteSones.containsKey(sone.getId());
547                 }
548         }
549
550         /**
551          * Returns whether the Sone with the given ID is a remote Sone.
552          *
553          * @param id
554          *            The ID of the Sone to check
555          * @return {@code true} if the Sone with the given ID is a remote Sone,
556          *         {@code false} otherwise
557          */
558         public boolean isRemoteSone(String id) {
559                 synchronized (remoteSones) {
560                         return remoteSones.containsKey(id);
561                 }
562         }
563
564         /**
565          * Returns whether the Sone with the given ID is a new Sone.
566          *
567          * @param soneId
568          *            The ID of the sone to check for
569          * @return {@code true} if the given Sone is new, false otherwise
570          */
571         public boolean isNewSone(String soneId) {
572                 synchronized (newSones) {
573                         return !knownSones.contains(soneId) && newSones.contains(soneId);
574                 }
575         }
576
577         /**
578          * Returns whether the given Sone has been modified.
579          *
580          * @param sone
581          *            The Sone to check for modifications
582          * @return {@code true} if a modification has been detected in the Sone,
583          *         {@code false} otherwise
584          */
585         public boolean isModifiedSone(Sone sone) {
586                 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
587         }
588
589         /**
590          * Returns whether the target Sone is trusted by the origin Sone.
591          *
592          * @param origin
593          *            The origin Sone
594          * @param target
595          *            The target Sone
596          * @return {@code true} if the target Sone is trusted by the origin Sone
597          */
598         public boolean isSoneTrusted(Sone origin, Sone target) {
599                 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
600                 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
601         }
602
603         /**
604          * Returns the post with the given ID.
605          *
606          * @param postId
607          *            The ID of the post to get
608          * @return The post with the given ID, or a new post with the given ID
609          */
610         public Post getPost(String postId) {
611                 return getPost(postId, true);
612         }
613
614         /**
615          * Returns the post with the given ID, optionally creating a new post.
616          *
617          * @param postId
618          *            The ID of the post to get
619          * @param create
620          *            {@code true} it create a new post if no post with the given ID
621          *            exists, {@code false} to return {@code null}
622          * @return The post, or {@code null} if there is no such post
623          */
624         @Override
625         public Post getPost(String postId, boolean create) {
626                 synchronized (posts) {
627                         Post post = posts.get(postId);
628                         if ((post == null) && create) {
629                                 post = new Post(postId);
630                                 posts.put(postId, post);
631                         }
632                         return post;
633                 }
634         }
635
636         /**
637          * Returns whether the given post ID is new.
638          *
639          * @param postId
640          *            The post ID
641          * @return {@code true} if the post is considered to be new, {@code false}
642          *         otherwise
643          */
644         public boolean isNewPost(String postId) {
645                 synchronized (newPosts) {
646                         return !knownPosts.contains(postId) && newPosts.contains(postId);
647                 }
648         }
649
650         /**
651          * Returns all posts that have the given Sone as recipient.
652          *
653          * @see Post#getRecipient()
654          * @param recipient
655          *            The recipient of the posts
656          * @return All posts that have the given Sone as recipient
657          */
658         public Set<Post> getDirectedPosts(Sone recipient) {
659                 Validation.begin().isNotNull("Recipient", recipient).check();
660                 Set<Post> directedPosts = new HashSet<Post>();
661                 synchronized (posts) {
662                         for (Post post : posts.values()) {
663                                 if (recipient.equals(post.getRecipient())) {
664                                         directedPosts.add(post);
665                                 }
666                         }
667                 }
668                 return directedPosts;
669         }
670
671         /**
672          * Returns the reply with the given ID. If there is no reply with the given
673          * ID yet, a new one is created.
674          *
675          * @param replyId
676          *            The ID of the reply to get
677          * @return The reply
678          */
679         public Reply getReply(String replyId) {
680                 return getReply(replyId, true);
681         }
682
683         /**
684          * Returns the reply with the given ID. If there is no reply with the given
685          * ID yet, a new one is created, unless {@code create} is false in which
686          * case {@code null} is returned.
687          *
688          * @param replyId
689          *            The ID of the reply to get
690          * @param create
691          *            {@code true} to always return a {@link Reply}, {@code false}
692          *            to return {@code null} if no reply can be found
693          * @return The reply, or {@code null} if there is no such reply
694          */
695         public Reply getReply(String replyId, boolean create) {
696                 synchronized (replies) {
697                         Reply reply = replies.get(replyId);
698                         if (create && (reply == null)) {
699                                 reply = new Reply(replyId);
700                                 replies.put(replyId, reply);
701                         }
702                         return reply;
703                 }
704         }
705
706         /**
707          * Returns all replies for the given post, order ascending by time.
708          *
709          * @param post
710          *            The post to get all replies for
711          * @return All replies for the given post
712          */
713         public List<Reply> getReplies(Post post) {
714                 Set<Sone> sones = getSones();
715                 List<Reply> replies = new ArrayList<Reply>();
716                 for (Sone sone : sones) {
717                         for (Reply reply : sone.getReplies()) {
718                                 if (reply.getPost().equals(post)) {
719                                         replies.add(reply);
720                                 }
721                         }
722                 }
723                 Collections.sort(replies, Reply.TIME_COMPARATOR);
724                 return replies;
725         }
726
727         /**
728          * Returns whether the reply with the given ID is new.
729          *
730          * @param replyId
731          *            The ID of the reply to check
732          * @return {@code true} if the reply is considered to be new, {@code false}
733          *         otherwise
734          */
735         public boolean isNewReply(String replyId) {
736                 synchronized (newReplies) {
737                         return !knownReplies.contains(replyId) && newReplies.contains(replyId);
738                 }
739         }
740
741         /**
742          * Returns all Sones that have liked the given post.
743          *
744          * @param post
745          *            The post to get the liking Sones for
746          * @return The Sones that like the given post
747          */
748         public Set<Sone> getLikes(Post post) {
749                 Set<Sone> sones = new HashSet<Sone>();
750                 for (Sone sone : getSones()) {
751                         if (sone.getLikedPostIds().contains(post.getId())) {
752                                 sones.add(sone);
753                         }
754                 }
755                 return sones;
756         }
757
758         /**
759          * Returns all Sones that have liked the given reply.
760          *
761          * @param reply
762          *            The reply to get the liking Sones for
763          * @return The Sones that like the given reply
764          */
765         public Set<Sone> getLikes(Reply reply) {
766                 Set<Sone> sones = new HashSet<Sone>();
767                 for (Sone sone : getSones()) {
768                         if (sone.getLikedReplyIds().contains(reply.getId())) {
769                                 sones.add(sone);
770                         }
771                 }
772                 return sones;
773         }
774
775         /**
776          * Returns whether the given post is bookmarked.
777          *
778          * @param post
779          *            The post to check
780          * @return {@code true} if the given post is bookmarked, {@code false}
781          *         otherwise
782          */
783         public boolean isBookmarked(Post post) {
784                 return isPostBookmarked(post.getId());
785         }
786
787         /**
788          * Returns whether the post with the given ID is bookmarked.
789          *
790          * @param id
791          *            The ID of the post to check
792          * @return {@code true} if the post with the given ID is bookmarked,
793          *         {@code false} otherwise
794          */
795         public boolean isPostBookmarked(String id) {
796                 synchronized (bookmarkedPosts) {
797                         return bookmarkedPosts.contains(id);
798                 }
799         }
800
801         /**
802          * Returns all currently known bookmarked posts.
803          *
804          * @return All bookmarked posts
805          */
806         public Set<Post> getBookmarkedPosts() {
807                 Set<Post> posts = new HashSet<Post>();
808                 synchronized (bookmarkedPosts) {
809                         for (String bookmarkedPostId : bookmarkedPosts) {
810                                 Post post = getPost(bookmarkedPostId, false);
811                                 if (post != null) {
812                                         posts.add(post);
813                                 }
814                         }
815                 }
816                 return posts;
817         }
818
819         /**
820          * Returns the album with the given ID, creating a new album if no album
821          * with the given ID can be found.
822          *
823          * @param albumId
824          *            The ID of the album
825          * @return The album with the given ID
826          */
827         public Album getAlbum(String albumId) {
828                 return getAlbum(albumId, true);
829         }
830
831         /**
832          * Returns the album with the given ID, optionally creating a new album if
833          * an album with the given ID can not be found.
834          *
835          * @param albumId
836          *            The ID of the album
837          * @param create
838          *            {@code true} to create a new album if none exists for the
839          *            given ID
840          * @return The album with the given ID, or {@code null} if no album with the
841          *         given ID exists and {@code create} is {@code false}
842          */
843         public Album getAlbum(String albumId, boolean create) {
844                 synchronized (albums) {
845                         Album album = albums.get(albumId);
846                         if (create && (album == null)) {
847                                 album = new Album(albumId);
848                                 albums.put(albumId, album);
849                         }
850                         return album;
851                 }
852         }
853
854         /**
855          * Returns the image with the given ID, creating it if necessary.
856          *
857          * @param imageId
858          *            The ID of the image
859          * @return The image with the given ID
860          */
861         public Image getImage(String imageId) {
862                 return getImage(imageId, true);
863         }
864
865         /**
866          * Returns the image with the given ID, optionally creating it if it does
867          * not exist.
868          *
869          * @param imageId
870          *            The ID of the image
871          * @param create
872          *            {@code true} to create an image if none exists with the given
873          *            ID
874          * @return The image with the given ID, or {@code null} if none exists and
875          *         none was created
876          */
877         public Image getImage(String imageId, boolean create) {
878                 synchronized (images) {
879                         Image image = images.get(imageId);
880                         if (create && (image == null)) {
881                                 image = new Image(imageId);
882                                 images.put(imageId, image);
883                         }
884                         return image;
885                 }
886         }
887
888         /**
889          * Returns the temporary image with the given ID.
890          *
891          * @param imageId
892          *            The ID of the temporary image
893          * @return The temporary image, or {@code null} if there is no temporary
894          *         image with the given ID
895          */
896         public TemporaryImage getTemporaryImage(String imageId) {
897                 synchronized (temporaryImages) {
898                         return temporaryImages.get(imageId);
899                 }
900         }
901
902         //
903         // ACTIONS
904         //
905
906         /**
907          * Locks the given Sone. A locked Sone will not be inserted by
908          * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
909          * again.
910          *
911          * @param sone
912          *            The sone to lock
913          */
914         public void lockSone(Sone sone) {
915                 synchronized (lockedSones) {
916                         if (lockedSones.add(sone)) {
917                                 coreListenerManager.fireSoneLocked(sone);
918                         }
919                 }
920         }
921
922         /**
923          * Unlocks the given Sone.
924          *
925          * @see #lockSone(Sone)
926          * @param sone
927          *            The sone to unlock
928          */
929         public void unlockSone(Sone sone) {
930                 synchronized (lockedSones) {
931                         if (lockedSones.remove(sone)) {
932                                 coreListenerManager.fireSoneUnlocked(sone);
933                         }
934                 }
935         }
936
937         /**
938          * Adds a local Sone from the given ID which has to be the ID of an own
939          * identity.
940          *
941          * @param id
942          *            The ID of an own identity to add a Sone for
943          * @return The added (or already existing) Sone
944          */
945         public Sone addLocalSone(String id) {
946                 synchronized (localSones) {
947                         if (localSones.containsKey(id)) {
948                                 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
949                                 return localSones.get(id);
950                         }
951                         OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
952                         if (ownIdentity == null) {
953                                 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
954                                 return null;
955                         }
956                         return addLocalSone(ownIdentity);
957                 }
958         }
959
960         /**
961          * Adds a local Sone from the given own identity.
962          *
963          * @param ownIdentity
964          *            The own identity to create a Sone from
965          * @return The added (or already existing) Sone
966          */
967         public Sone addLocalSone(OwnIdentity ownIdentity) {
968                 if (ownIdentity == null) {
969                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
970                         return null;
971                 }
972                 synchronized (localSones) {
973                         final Sone sone;
974                         try {
975                                 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
976                         } catch (MalformedURLException mue1) {
977                                 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
978                                 return null;
979                         }
980                         sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
981                         sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
982                         /* TODO - load posts ’n stuff */
983                         localSones.put(ownIdentity.getId(), sone);
984                         final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
985                         soneInserter.addSoneInsertListener(this);
986                         soneInserters.put(sone, soneInserter);
987                         setSoneStatus(sone, SoneStatus.idle);
988                         loadSone(sone);
989                         soneInserter.start();
990                         return sone;
991                 }
992         }
993
994         /**
995          * Creates a new Sone for the given own identity.
996          *
997          * @param ownIdentity
998          *            The own identity to create a Sone for
999          * @return The created Sone
1000          */
1001         public Sone createSone(OwnIdentity ownIdentity) {
1002                 try {
1003                         ownIdentity.addContext("Sone");
1004                 } catch (WebOfTrustException wote1) {
1005                         logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
1006                         return null;
1007                 }
1008                 Sone sone = addLocalSone(ownIdentity);
1009                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1010                 sone.addFriend("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
1011                 touchConfiguration();
1012                 return sone;
1013         }
1014
1015         /**
1016          * Adds the Sone of the given identity.
1017          *
1018          * @param identity
1019          *            The identity whose Sone to add
1020          * @return The added or already existing Sone
1021          */
1022         public Sone addRemoteSone(Identity identity) {
1023                 if (identity == null) {
1024                         logger.log(Level.WARNING, "Given Identity is null!");
1025                         return null;
1026                 }
1027                 synchronized (remoteSones) {
1028                         final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
1029                         boolean newSone = sone.getRequestUri() == null;
1030                         sone.setRequestUri(getSoneUri(identity.getRequestUri()));
1031                         sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
1032                         if (newSone) {
1033                                 synchronized (newSones) {
1034                                         newSone = !knownSones.contains(sone.getId());
1035                                         if (newSone) {
1036                                                 newSones.add(sone.getId());
1037                                         }
1038                                 }
1039                                 if (newSone) {
1040                                         coreListenerManager.fireNewSoneFound(sone);
1041                                         for (Sone localSone : getLocalSones()) {
1042                                                 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
1043                                                         localSone.addFriend(sone.getId());
1044                                                         touchConfiguration();
1045                                                 }
1046                                         }
1047                                 }
1048                         }
1049                         remoteSones.put(identity.getId(), sone);
1050                         soneDownloader.addSone(sone);
1051                         setSoneStatus(sone, SoneStatus.unknown);
1052                         soneDownloaders.execute(new Runnable() {
1053
1054                                 @Override
1055                                 @SuppressWarnings("synthetic-access")
1056                                 public void run() {
1057                                         soneDownloader.fetchSone(sone, sone.getRequestUri());
1058                                 }
1059
1060                         });
1061                         return sone;
1062                 }
1063         }
1064
1065         /**
1066          * Retrieves the trust relationship from the origin to the target. If the
1067          * trust relationship can not be retrieved, {@code null} is returned.
1068          *
1069          * @see Identity#getTrust(OwnIdentity)
1070          * @param origin
1071          *            The origin of the trust tree
1072          * @param target
1073          *            The target of the trust
1074          * @return The trust relationship
1075          */
1076         public Trust getTrust(Sone origin, Sone target) {
1077                 if (!isLocalSone(origin)) {
1078                         logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
1079                         return null;
1080                 }
1081                 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
1082         }
1083
1084         /**
1085          * Sets the trust value of the given origin Sone for the target Sone.
1086          *
1087          * @param origin
1088          *            The origin Sone
1089          * @param target
1090          *            The target Sone
1091          * @param trustValue
1092          *            The trust value (from {@code -100} to {@code 100})
1093          */
1094         public void setTrust(Sone origin, Sone target, int trustValue) {
1095                 Validation.begin().isNotNull("Trust Origin", origin).check().isInstanceOf("Trust Origin", origin.getIdentity(), OwnIdentity.class).isNotNull("Trust Target", target).isLessOrEqual("Trust Value", trustValue, 100).isGreaterOrEqual("Trust Value", trustValue, -100).check();
1096                 try {
1097                         ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, preferences.getTrustComment());
1098                 } catch (WebOfTrustException wote1) {
1099                         logger.log(Level.WARNING, "Could not set trust for Sone: " + target, wote1);
1100                 }
1101         }
1102
1103         /**
1104          * Removes any trust assignment for the given target Sone.
1105          *
1106          * @param origin
1107          *            The trust origin
1108          * @param target
1109          *            The trust target
1110          */
1111         public void removeTrust(Sone origin, Sone target) {
1112                 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1113                 try {
1114                         ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
1115                 } catch (WebOfTrustException wote1) {
1116                         logger.log(Level.WARNING, "Could not remove trust for Sone: " + target, wote1);
1117                 }
1118         }
1119
1120         /**
1121          * Assigns the configured positive trust value for the given target.
1122          *
1123          * @param origin
1124          *            The trust origin
1125          * @param target
1126          *            The trust target
1127          */
1128         public void trustSone(Sone origin, Sone target) {
1129                 setTrust(origin, target, preferences.getPositiveTrust());
1130         }
1131
1132         /**
1133          * Assigns the configured negative trust value for the given target.
1134          *
1135          * @param origin
1136          *            The trust origin
1137          * @param target
1138          *            The trust target
1139          */
1140         public void distrustSone(Sone origin, Sone target) {
1141                 setTrust(origin, target, preferences.getNegativeTrust());
1142         }
1143
1144         /**
1145          * Removes the trust assignment for the given target.
1146          *
1147          * @param origin
1148          *            The trust origin
1149          * @param target
1150          *            The trust target
1151          */
1152         public void untrustSone(Sone origin, Sone target) {
1153                 removeTrust(origin, target);
1154         }
1155
1156         /**
1157          * Updates the stored Sone with the given Sone.
1158          *
1159          * @param sone
1160          *            The updated Sone
1161          */
1162         public void updateSone(Sone sone) {
1163                 updateSone(sone, false);
1164         }
1165
1166         /**
1167          * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1168          * {@code true}, an older Sone than the current Sone can be given to restore
1169          * an old state.
1170          *
1171          * @param sone
1172          *            The Sone to update
1173          * @param soneRescueMode
1174          *            {@code true} if the stored Sone should be updated regardless
1175          *            of the age of the given Sone
1176          */
1177         public void updateSone(Sone sone, boolean soneRescueMode) {
1178                 if (hasSone(sone.getId())) {
1179                         Sone storedSone = getSone(sone.getId());
1180                         if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1181                                 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
1182                                 return;
1183                         }
1184                         synchronized (posts) {
1185                                 if (!soneRescueMode) {
1186                                         for (Post post : storedSone.getPosts()) {
1187                                                 posts.remove(post.getId());
1188                                                 if (!sone.getPosts().contains(post)) {
1189                                                         coreListenerManager.firePostRemoved(post);
1190                                                 }
1191                                         }
1192                                 }
1193                                 List<Post> storedPosts = storedSone.getPosts();
1194                                 synchronized (newPosts) {
1195                                         for (Post post : sone.getPosts()) {
1196                                                 post.setSone(storedSone);
1197                                                 if (!storedPosts.contains(post) && !knownPosts.contains(post.getId())) {
1198                                                         newPosts.add(post.getId());
1199                                                         coreListenerManager.fireNewPostFound(post);
1200                                                 }
1201                                                 posts.put(post.getId(), post);
1202                                         }
1203                                 }
1204                         }
1205                         synchronized (replies) {
1206                                 if (!soneRescueMode) {
1207                                         for (Reply reply : storedSone.getReplies()) {
1208                                                 replies.remove(reply.getId());
1209                                                 if (!sone.getReplies().contains(reply)) {
1210                                                         coreListenerManager.fireReplyRemoved(reply);
1211                                                 }
1212                                         }
1213                                 }
1214                                 Set<Reply> storedReplies = storedSone.getReplies();
1215                                 synchronized (newReplies) {
1216                                         for (Reply reply : sone.getReplies()) {
1217                                                 reply.setSone(storedSone);
1218                                                 if (!storedReplies.contains(reply) && !knownReplies.contains(reply.getId())) {
1219                                                         newReplies.add(reply.getId());
1220                                                         coreListenerManager.fireNewReplyFound(reply);
1221                                                 }
1222                                                 replies.put(reply.getId(), reply);
1223                                         }
1224                                 }
1225                         }
1226                         synchronized (albums) {
1227                                 synchronized (images) {
1228                                         for (Album album : storedSone.getAlbums()) {
1229                                                 albums.remove(album.getId());
1230                                                 for (Image image : album.getImages()) {
1231                                                         images.remove(image.getId());
1232                                                 }
1233                                         }
1234                                         for (Album album : sone.getAlbums()) {
1235                                                 albums.put(album.getId(), album);
1236                                                 for (Image image : album.getImages()) {
1237                                                         images.put(image.getId(), image);
1238                                                 }
1239                                         }
1240                                 }
1241                         }
1242                         synchronized (storedSone) {
1243                                 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1244                                         storedSone.setTime(sone.getTime());
1245                                 }
1246                                 storedSone.setClient(sone.getClient());
1247                                 storedSone.setProfile(sone.getProfile());
1248                                 if (soneRescueMode) {
1249                                         for (Post post : sone.getPosts()) {
1250                                                 storedSone.addPost(post);
1251                                         }
1252                                         for (Reply reply : sone.getReplies()) {
1253                                                 storedSone.addReply(reply);
1254                                         }
1255                                         for (String likedPostId : sone.getLikedPostIds()) {
1256                                                 storedSone.addLikedPostId(likedPostId);
1257                                         }
1258                                         for (String likedReplyId : sone.getLikedReplyIds()) {
1259                                                 storedSone.addLikedReplyId(likedReplyId);
1260                                         }
1261                                         for (Album album : sone.getAlbums()) {
1262                                                 storedSone.addAlbum(album);
1263                                         }
1264                                 } else {
1265                                         storedSone.setPosts(sone.getPosts());
1266                                         storedSone.setReplies(sone.getReplies());
1267                                         storedSone.setLikePostIds(sone.getLikedPostIds());
1268                                         storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1269                                         storedSone.setAlbums(sone.getAlbums());
1270                                 }
1271                                 storedSone.setLatestEdition(sone.getLatestEdition());
1272                         }
1273                 }
1274         }
1275
1276         /**
1277          * Deletes the given Sone. This will remove the Sone from the
1278          * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1279          * and remove the context from its identity.
1280          *
1281          * @param sone
1282          *            The Sone to delete
1283          */
1284         public void deleteSone(Sone sone) {
1285                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1286                         logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1287                         return;
1288                 }
1289                 synchronized (localSones) {
1290                         if (!localSones.containsKey(sone.getId())) {
1291                                 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1292                                 return;
1293                         }
1294                         localSones.remove(sone.getId());
1295                         SoneInserter soneInserter = soneInserters.remove(sone);
1296                         soneInserter.removeSoneInsertListener(this);
1297                         soneInserter.stop();
1298                 }
1299                 try {
1300                         ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1301                         ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1302                 } catch (WebOfTrustException wote1) {
1303                         logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1304                 }
1305                 try {
1306                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1307                 } catch (ConfigurationException ce1) {
1308                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1309                 }
1310         }
1311
1312         /**
1313          * Marks the given Sone as known. If the Sone was {@link #isNewPost(String)
1314          * new} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1315          *
1316          * @param sone
1317          *            The Sone to mark as known
1318          */
1319         public void markSoneKnown(Sone sone) {
1320                 synchronized (newSones) {
1321                         if (newSones.remove(sone.getId())) {
1322                                 knownSones.add(sone.getId());
1323                                 coreListenerManager.fireMarkSoneKnown(sone);
1324                                 touchConfiguration();
1325                         }
1326                 }
1327         }
1328
1329         /**
1330          * Loads and updates the given Sone from the configuration. If any error is
1331          * encountered, loading is aborted and the given Sone is not changed.
1332          *
1333          * @param sone
1334          *            The Sone to load and update
1335          */
1336         public void loadSone(Sone sone) {
1337                 if (!isLocalSone(sone)) {
1338                         logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1339                         return;
1340                 }
1341
1342                 /* initialize options. */
1343                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1344                 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1345
1346                 /* load Sone. */
1347                 String sonePrefix = "Sone/" + sone.getId();
1348                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1349                 if (soneTime == null) {
1350                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1351                         return;
1352                 }
1353                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1354
1355                 /* load profile. */
1356                 Profile profile = new Profile();
1357                 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1358                 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1359                 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1360                 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1361                 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1362                 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1363
1364                 /* load profile fields. */
1365                 while (true) {
1366                         String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1367                         String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1368                         if (fieldName == null) {
1369                                 break;
1370                         }
1371                         String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1372                         profile.addField(fieldName).setValue(fieldValue);
1373                 }
1374
1375                 /* load posts. */
1376                 Set<Post> posts = new HashSet<Post>();
1377                 while (true) {
1378                         String postPrefix = sonePrefix + "/Posts/" + posts.size();
1379                         String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1380                         if (postId == null) {
1381                                 break;
1382                         }
1383                         String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1384                         long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1385                         String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1386                         if ((postTime == 0) || (postText == null)) {
1387                                 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1388                                 return;
1389                         }
1390                         Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1391                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1392                                 post.setRecipient(getSone(postRecipientId));
1393                         }
1394                         posts.add(post);
1395                 }
1396
1397                 /* load replies. */
1398                 Set<Reply> replies = new HashSet<Reply>();
1399                 while (true) {
1400                         String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1401                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1402                         if (replyId == null) {
1403                                 break;
1404                         }
1405                         String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1406                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1407                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1408                         if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1409                                 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1410                                 return;
1411                         }
1412                         replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1413                 }
1414
1415                 /* load post likes. */
1416                 Set<String> likedPostIds = new HashSet<String>();
1417                 while (true) {
1418                         String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1419                         if (likedPostId == null) {
1420                                 break;
1421                         }
1422                         likedPostIds.add(likedPostId);
1423                 }
1424
1425                 /* load reply likes. */
1426                 Set<String> likedReplyIds = new HashSet<String>();
1427                 while (true) {
1428                         String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1429                         if (likedReplyId == null) {
1430                                 break;
1431                         }
1432                         likedReplyIds.add(likedReplyId);
1433                 }
1434
1435                 /* load friends. */
1436                 Set<String> friends = new HashSet<String>();
1437                 while (true) {
1438                         String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1439                         if (friendId == null) {
1440                                 break;
1441                         }
1442                         friends.add(friendId);
1443                 }
1444
1445                 /* load albums. */
1446                 List<Album> topLevelAlbums = new ArrayList<Album>();
1447                 int albumCounter = 0;
1448                 while (true) {
1449                         String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1450                         String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1451                         if (albumId == null) {
1452                                 break;
1453                         }
1454                         String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1455                         String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1456                         String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1457                         String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1458                         if ((albumTitle == null) || (albumDescription == null)) {
1459                                 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1460                                 return;
1461                         }
1462                         Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1463                         if (albumParentId != null) {
1464                                 Album parentAlbum = getAlbum(albumParentId, false);
1465                                 if (parentAlbum == null) {
1466                                         logger.log(Level.WARNING, "Invalid parent album ID: " + albumParentId);
1467                                         return;
1468                                 }
1469                                 parentAlbum.addAlbum(album);
1470                         } else {
1471                                 topLevelAlbums.add(album);
1472                         }
1473                 }
1474
1475                 /* load images. */
1476                 int imageCounter = 0;
1477                 while (true) {
1478                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1479                         String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1480                         if (imageId == null) {
1481                                 break;
1482                         }
1483                         String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1484                         String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1485                         String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1486                         String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1487                         Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1488                         Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1489                         Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1490                         if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1491                                 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1492                                 return;
1493                         }
1494                         Album album = getAlbum(albumId, false);
1495                         if (album == null) {
1496                                 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1497                                 return;
1498                         }
1499                         Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1500                         image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1501                         album.addImage(image);
1502                 }
1503
1504                 /* load options. */
1505                 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1506                 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1507
1508                 /* if we’re still here, Sone was loaded successfully. */
1509                 synchronized (sone) {
1510                         sone.setTime(soneTime);
1511                         sone.setProfile(profile);
1512                         sone.setPosts(posts);
1513                         sone.setReplies(replies);
1514                         sone.setLikePostIds(likedPostIds);
1515                         sone.setLikeReplyIds(likedReplyIds);
1516                         sone.setFriends(friends);
1517                         sone.setAlbums(topLevelAlbums);
1518                         soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1519                 }
1520                 synchronized (newSones) {
1521                         for (String friend : friends) {
1522                                 knownSones.add(friend);
1523                         }
1524                 }
1525                 synchronized (newPosts) {
1526                         for (Post post : posts) {
1527                                 knownPosts.add(post.getId());
1528                         }
1529                 }
1530                 synchronized (newReplies) {
1531                         for (Reply reply : replies) {
1532                                 knownReplies.add(reply.getId());
1533                         }
1534                 }
1535         }
1536
1537         /**
1538          * Creates a new post.
1539          *
1540          * @param sone
1541          *            The Sone that creates the post
1542          * @param text
1543          *            The text of the post
1544          * @return The created post
1545          */
1546         public Post createPost(Sone sone, String text) {
1547                 return createPost(sone, System.currentTimeMillis(), text);
1548         }
1549
1550         /**
1551          * Creates a new post.
1552          *
1553          * @param sone
1554          *            The Sone that creates the post
1555          * @param time
1556          *            The time of the post
1557          * @param text
1558          *            The text of the post
1559          * @return The created post
1560          */
1561         public Post createPost(Sone sone, long time, String text) {
1562                 return createPost(sone, null, time, text);
1563         }
1564
1565         /**
1566          * Creates a new post.
1567          *
1568          * @param sone
1569          *            The Sone that creates the post
1570          * @param recipient
1571          *            The recipient Sone, or {@code null} if this post does not have
1572          *            a recipient
1573          * @param text
1574          *            The text of the post
1575          * @return The created post
1576          */
1577         public Post createPost(Sone sone, Sone recipient, String text) {
1578                 return createPost(sone, recipient, System.currentTimeMillis(), text);
1579         }
1580
1581         /**
1582          * Creates a new post.
1583          *
1584          * @param sone
1585          *            The Sone that creates the post
1586          * @param recipient
1587          *            The recipient Sone, or {@code null} if this post does not have
1588          *            a recipient
1589          * @param time
1590          *            The time of the post
1591          * @param text
1592          *            The text of the post
1593          * @return The created post
1594          */
1595         public Post createPost(Sone sone, Sone recipient, long time, String text) {
1596                 if (!isLocalSone(sone)) {
1597                         logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1598                         return null;
1599                 }
1600                 final Post post = new Post(sone, time, text);
1601                 if (recipient != null) {
1602                         post.setRecipient(recipient);
1603                 }
1604                 synchronized (posts) {
1605                         posts.put(post.getId(), post);
1606                 }
1607                 synchronized (newPosts) {
1608                         newPosts.add(post.getId());
1609                         coreListenerManager.fireNewPostFound(post);
1610                 }
1611                 sone.addPost(post);
1612                 touchConfiguration();
1613                 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1614
1615                         /**
1616                          * {@inheritDoc}
1617                          */
1618                         @Override
1619                         public void run() {
1620                                 markPostKnown(post);
1621                         }
1622                 }, "Mark " + post + " read.");
1623                 return post;
1624         }
1625
1626         /**
1627          * Deletes the given post.
1628          *
1629          * @param post
1630          *            The post to delete
1631          */
1632         public void deletePost(Post post) {
1633                 if (!isLocalSone(post.getSone())) {
1634                         logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1635                         return;
1636                 }
1637                 post.getSone().removePost(post);
1638                 synchronized (posts) {
1639                         posts.remove(post.getId());
1640                 }
1641                 coreListenerManager.firePostRemoved(post);
1642                 synchronized (newPosts) {
1643                         markPostKnown(post);
1644                         knownPosts.remove(post.getId());
1645                 }
1646                 touchConfiguration();
1647         }
1648
1649         /**
1650          * Marks the given post as known, if it is currently a new post (according
1651          * to {@link #isNewPost(String)}).
1652          *
1653          * @param post
1654          *            The post to mark as known
1655          */
1656         public void markPostKnown(Post post) {
1657                 synchronized (newPosts) {
1658                         if (newPosts.remove(post.getId())) {
1659                                 knownPosts.add(post.getId());
1660                                 coreListenerManager.fireMarkPostKnown(post);
1661                                 touchConfiguration();
1662                         }
1663                 }
1664         }
1665
1666         /**
1667          * Bookmarks the given post.
1668          *
1669          * @param post
1670          *            The post to bookmark
1671          */
1672         public void bookmark(Post post) {
1673                 bookmarkPost(post.getId());
1674         }
1675
1676         /**
1677          * Bookmarks the post with the given ID.
1678          *
1679          * @param id
1680          *            The ID of the post to bookmark
1681          */
1682         public void bookmarkPost(String id) {
1683                 synchronized (bookmarkedPosts) {
1684                         bookmarkedPosts.add(id);
1685                 }
1686         }
1687
1688         /**
1689          * Removes the given post from the bookmarks.
1690          *
1691          * @param post
1692          *            The post to unbookmark
1693          */
1694         public void unbookmark(Post post) {
1695                 unbookmarkPost(post.getId());
1696         }
1697
1698         /**
1699          * Removes the post with the given ID from the bookmarks.
1700          *
1701          * @param id
1702          *            The ID of the post to unbookmark
1703          */
1704         public void unbookmarkPost(String id) {
1705                 synchronized (bookmarkedPosts) {
1706                         bookmarkedPosts.remove(id);
1707                 }
1708         }
1709
1710         /**
1711          * Creates a new reply.
1712          *
1713          * @param sone
1714          *            The Sone that creates the reply
1715          * @param post
1716          *            The post that this reply refers to
1717          * @param text
1718          *            The text of the reply
1719          * @return The created reply
1720          */
1721         public Reply createReply(Sone sone, Post post, String text) {
1722                 return createReply(sone, post, System.currentTimeMillis(), text);
1723         }
1724
1725         /**
1726          * Creates a new reply.
1727          *
1728          * @param sone
1729          *            The Sone that creates the reply
1730          * @param post
1731          *            The post that this reply refers to
1732          * @param time
1733          *            The time of the reply
1734          * @param text
1735          *            The text of the reply
1736          * @return The created reply
1737          */
1738         public Reply createReply(Sone sone, Post post, long time, String text) {
1739                 if (!isLocalSone(sone)) {
1740                         logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1741                         return null;
1742                 }
1743                 final Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1744                 synchronized (replies) {
1745                         replies.put(reply.getId(), reply);
1746                 }
1747                 synchronized (newReplies) {
1748                         newReplies.add(reply.getId());
1749                         coreListenerManager.fireNewReplyFound(reply);
1750                 }
1751                 sone.addReply(reply);
1752                 touchConfiguration();
1753                 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1754
1755                         /**
1756                          * {@inheritDoc}
1757                          */
1758                         @Override
1759                         public void run() {
1760                                 markReplyKnown(reply);
1761                         }
1762                 }, "Mark " + reply + " read.");
1763                 return reply;
1764         }
1765
1766         /**
1767          * Deletes the given reply.
1768          *
1769          * @param reply
1770          *            The reply to delete
1771          */
1772         public void deleteReply(Reply reply) {
1773                 Sone sone = reply.getSone();
1774                 if (!isLocalSone(sone)) {
1775                         logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1776                         return;
1777                 }
1778                 synchronized (replies) {
1779                         replies.remove(reply.getId());
1780                 }
1781                 synchronized (newReplies) {
1782                         markReplyKnown(reply);
1783                         knownReplies.remove(reply.getId());
1784                 }
1785                 sone.removeReply(reply);
1786                 touchConfiguration();
1787         }
1788
1789         /**
1790          * Marks the given reply as known, if it is currently a new reply (according
1791          * to {@link #isNewReply(String)}).
1792          *
1793          * @param reply
1794          *            The reply to mark as known
1795          */
1796         public void markReplyKnown(Reply reply) {
1797                 synchronized (newReplies) {
1798                         if (newReplies.remove(reply.getId())) {
1799                                 knownReplies.add(reply.getId());
1800                                 coreListenerManager.fireMarkReplyKnown(reply);
1801                                 touchConfiguration();
1802                         }
1803                 }
1804         }
1805
1806         /**
1807          * Creates a new top-level album for the given Sone.
1808          *
1809          * @param sone
1810          *            The Sone to create the album for
1811          * @return The new album
1812          */
1813         public Album createAlbum(Sone sone) {
1814                 return createAlbum(sone, null);
1815         }
1816
1817         /**
1818          * Creates a new album for the given Sone.
1819          *
1820          * @param sone
1821          *            The Sone to create the album for
1822          * @param parent
1823          *            The parent of the album (may be {@code null} to create a
1824          *            top-level album)
1825          * @return The new album
1826          */
1827         public Album createAlbum(Sone sone, Album parent) {
1828                 Album album = new Album();
1829                 synchronized (albums) {
1830                         albums.put(album.getId(), album);
1831                 }
1832                 album.setSone(sone);
1833                 if (parent != null) {
1834                         parent.addAlbum(album);
1835                 } else {
1836                         sone.addAlbum(album);
1837                 }
1838                 return album;
1839         }
1840
1841         /**
1842          * Deletes the given album. The owner of the album has to be a local Sone,
1843          * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1844          *
1845          * @param album
1846          *            The album to remove
1847          */
1848         public void deleteAlbum(Album album) {
1849                 Validation.begin().isNotNull("Album", album).check().is("Local Sone", isLocalSone(album.getSone())).check();
1850                 if (!album.isEmpty()) {
1851                         return;
1852                 }
1853                 if (album.getParent() == null) {
1854                         album.getSone().removeAlbum(album);
1855                 } else {
1856                         album.getParent().removeAlbum(album);
1857                 }
1858                 synchronized (albums) {
1859                         albums.remove(album.getId());
1860                 }
1861                 saveSone(album.getSone());
1862         }
1863
1864         /**
1865          * Creates a new image.
1866          *
1867          * @param sone
1868          *            The Sone creating the image
1869          * @param album
1870          *            The album the image will be inserted into
1871          * @param temporaryImage
1872          *            The temporary image to create the image from
1873          * @return The newly created image
1874          */
1875         public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1876                 Validation.begin().isNotNull("Sone", sone).isNotNull("Album", album).isNotNull("Temporary Image", temporaryImage).check().is("Local Sone", isLocalSone(sone)).check().isEqual("Owner and Album Owner", sone, album.getSone()).check();
1877                 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1878                 album.addImage(image);
1879                 synchronized (images) {
1880                         images.put(image.getId(), image);
1881                 }
1882                 imageInserter.insertImage(temporaryImage, image);
1883                 return image;
1884         }
1885
1886         /**
1887          * Deletes the given image. This method will also delete a matching
1888          * temporary image.
1889          *
1890          * @see #deleteTemporaryImage(TemporaryImage)
1891          * @param image
1892          *            The image to delete
1893          */
1894         public void deleteImage(Image image) {
1895                 Validation.begin().isNotNull("Image", image).check().is("Local Sone", isLocalSone(image.getSone())).check();
1896                 deleteTemporaryImage(image.getId());
1897                 image.getAlbum().removeImage(image);
1898                 synchronized (images) {
1899                         images.remove(image.getId());
1900                 }
1901                 saveSone(image.getSone());
1902         }
1903
1904         /**
1905          * Creates a new temporary image.
1906          *
1907          * @param mimeType
1908          *            The MIME type of the temporary image
1909          * @param imageData
1910          *            The encoded data of the image
1911          * @return The temporary image
1912          */
1913         public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1914                 TemporaryImage temporaryImage = new TemporaryImage();
1915                 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1916                 synchronized (temporaryImages) {
1917                         temporaryImages.put(temporaryImage.getId(), temporaryImage);
1918                 }
1919                 return temporaryImage;
1920         }
1921
1922         /**
1923          * Deletes the given temporary image.
1924          *
1925          * @param temporaryImage
1926          *            The temporary image to delete
1927          */
1928         public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1929                 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1930                 deleteTemporaryImage(temporaryImage.getId());
1931         }
1932
1933         /**
1934          * Deletes the temporary image with the given ID.
1935          *
1936          * @param imageId
1937          *            The ID of the temporary image to delete
1938          */
1939         public void deleteTemporaryImage(String imageId) {
1940                 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1941                 synchronized (temporaryImages) {
1942                         temporaryImages.remove(imageId);
1943                 }
1944                 Image image = getImage(imageId, false);
1945                 if (image != null) {
1946                         imageInserter.cancelImageInsert(image);
1947                 }
1948         }
1949
1950         /**
1951          * Notifies the core that the configuration, either of the core or of a
1952          * single local Sone, has changed, and that the configuration should be
1953          * saved.
1954          */
1955         public void touchConfiguration() {
1956                 lastConfigurationUpdate = System.currentTimeMillis();
1957         }
1958
1959         //
1960         // SERVICE METHODS
1961         //
1962
1963         /**
1964          * Starts the core.
1965          */
1966         @Override
1967         public void serviceStart() {
1968                 loadConfiguration();
1969                 updateChecker.addUpdateListener(this);
1970                 updateChecker.start();
1971         }
1972
1973         /**
1974          * {@inheritDoc}
1975          */
1976         @Override
1977         public void serviceRun() {
1978                 long lastSaved = System.currentTimeMillis();
1979                 while (!shouldStop()) {
1980                         sleep(1000);
1981                         long now = System.currentTimeMillis();
1982                         if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1983                                 for (Sone localSone : getLocalSones()) {
1984                                         saveSone(localSone);
1985                                 }
1986                                 saveConfiguration();
1987                                 lastSaved = now;
1988                         }
1989                 }
1990         }
1991
1992         /**
1993          * Stops the core.
1994          */
1995         @Override
1996         public void serviceStop() {
1997                 synchronized (localSones) {
1998                         for (SoneInserter soneInserter : soneInserters.values()) {
1999                                 soneInserter.removeSoneInsertListener(this);
2000                                 soneInserter.stop();
2001                         }
2002                 }
2003                 updateChecker.stop();
2004                 updateChecker.removeUpdateListener(this);
2005                 soneDownloader.stop();
2006         }
2007
2008         //
2009         // PRIVATE METHODS
2010         //
2011
2012         /**
2013          * Saves the given Sone. This will persist all local settings for the given
2014          * Sone, such as the friends list and similar, private options.
2015          *
2016          * @param sone
2017          *            The Sone to save
2018          */
2019         private synchronized void saveSone(Sone sone) {
2020                 if (!isLocalSone(sone)) {
2021                         logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
2022                         return;
2023                 }
2024                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
2025                         logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
2026                         return;
2027                 }
2028
2029                 logger.log(Level.INFO, "Saving Sone: %s", sone);
2030                 try {
2031                         ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2032
2033                         /* save Sone into configuration. */
2034                         String sonePrefix = "Sone/" + sone.getId();
2035                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
2036                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
2037
2038                         /* save profile. */
2039                         Profile profile = sone.getProfile();
2040                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
2041                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
2042                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2043                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2044                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2045                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2046
2047                         /* save profile fields. */
2048                         int fieldCounter = 0;
2049                         for (Field profileField : profile.getFields()) {
2050                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2051                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2052                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2053                         }
2054                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2055
2056                         /* save posts. */
2057                         int postCounter = 0;
2058                         for (Post post : sone.getPosts()) {
2059                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2060                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2061                                 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2062                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2063                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2064                         }
2065                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2066
2067                         /* save replies. */
2068                         int replyCounter = 0;
2069                         for (Reply reply : sone.getReplies()) {
2070                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2071                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2072                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2073                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2074                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2075                         }
2076                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2077
2078                         /* save post likes. */
2079                         int postLikeCounter = 0;
2080                         for (String postId : sone.getLikedPostIds()) {
2081                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2082                         }
2083                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2084
2085                         /* save reply likes. */
2086                         int replyLikeCounter = 0;
2087                         for (String replyId : sone.getLikedReplyIds()) {
2088                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2089                         }
2090                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2091
2092                         /* save friends. */
2093                         int friendCounter = 0;
2094                         for (String friendId : sone.getFriends()) {
2095                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2096                         }
2097                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2098
2099                         /* save albums. first, collect in a flat structure, top-level first. */
2100                         List<Album> albums = Sone.flattenAlbums(sone.getAlbums());
2101
2102                         int albumCounter = 0;
2103                         for (Album album : albums) {
2104                                 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2105                                 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2106                                 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2107                                 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2108                                 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2109                                 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2110                         }
2111                         configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2112
2113                         /* save images. */
2114                         int imageCounter = 0;
2115                         for (Album album : albums) {
2116                                 for (Image image : album.getImages()) {
2117                                         if (!image.isInserted()) {
2118                                                 continue;
2119                                         }
2120                                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2121                                         configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2122                                         configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2123                                         configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2124                                         configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2125                                         configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2126                                         configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2127                                         configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2128                                         configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2129                                 }
2130                         }
2131                         configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2132
2133                         /* save options. */
2134                         configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2135                         configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2136
2137                         configuration.save();
2138                         logger.log(Level.INFO, "Sone %s saved.", sone);
2139                 } catch (ConfigurationException ce1) {
2140                         logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
2141                 } catch (WebOfTrustException wote1) {
2142                         logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
2143                 }
2144         }
2145
2146         /**
2147          * Saves the current options.
2148          */
2149         private void saveConfiguration() {
2150                 synchronized (configuration) {
2151                         if (storingConfiguration) {
2152                                 logger.log(Level.FINE, "Already storing configuration…");
2153                                 return;
2154                         }
2155                         storingConfiguration = true;
2156                 }
2157
2158                 /* store the options first. */
2159                 try {
2160                         configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2161                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2162                         configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2163                         configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2164                         configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2165                         configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2166                         configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2167                         configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2168                         configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2169                         configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2170                         configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
2171                         configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
2172                         configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
2173
2174                         /* save known Sones. */
2175                         int soneCounter = 0;
2176                         synchronized (newSones) {
2177                                 for (String knownSoneId : knownSones) {
2178                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2179                                 }
2180                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2181                         }
2182
2183                         /* save known posts. */
2184                         int postCounter = 0;
2185                         synchronized (newPosts) {
2186                                 for (String knownPostId : knownPosts) {
2187                                         configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2188                                 }
2189                                 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2190                         }
2191
2192                         /* save known replies. */
2193                         int replyCounter = 0;
2194                         synchronized (newReplies) {
2195                                 for (String knownReplyId : knownReplies) {
2196                                         configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2197                                 }
2198                                 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2199                         }
2200
2201                         /* save bookmarked posts. */
2202                         int bookmarkedPostCounter = 0;
2203                         synchronized (bookmarkedPosts) {
2204                                 for (String bookmarkedPostId : bookmarkedPosts) {
2205                                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2206                                 }
2207                         }
2208                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2209
2210                         /* now save it. */
2211                         configuration.save();
2212
2213                 } catch (ConfigurationException ce1) {
2214                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2215                 } finally {
2216                         synchronized (configuration) {
2217                                 storingConfiguration = false;
2218                         }
2219                 }
2220         }
2221
2222         /**
2223          * Loads the configuration.
2224          */
2225         @SuppressWarnings("unchecked")
2226         private void loadConfiguration() {
2227                 /* create options. */
2228                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2229
2230                         @Override
2231                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2232                                 SoneInserter.setInsertionDelay(newValue);
2233                         }
2234
2235                 }));
2236                 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2237                 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2238                 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2239                 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2240                 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2241                 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2242                 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2243
2244                         @Override
2245                         @SuppressWarnings("synthetic-access")
2246                         public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2247                                 fcpInterface.setActive(newValue);
2248                         }
2249                 }));
2250                 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2251
2252                         @Override
2253                         @SuppressWarnings("synthetic-access")
2254                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2255                                 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2256                         }
2257
2258                 }));
2259                 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
2260                 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
2261                 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
2262
2263                 /* read options from configuration. */
2264                 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
2265                 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
2266                 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
2267                 options.getBooleanOption("ClearOnNextRestart").set(null);
2268                 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
2269                 if (clearConfiguration) {
2270                         /* stop loading the configuration. */
2271                         return;
2272                 }
2273
2274                 loadConfigurationValue("InsertionDelay");
2275                 loadConfigurationValue("PostsPerPage");
2276                 loadConfigurationValue("CharactersPerPost");
2277                 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2278                 loadConfigurationValue("PositiveTrust");
2279                 loadConfigurationValue("NegativeTrust");
2280                 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2281                 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2282                 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2283                 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
2284
2285                 /* load known Sones. */
2286                 int soneCounter = 0;
2287                 while (true) {
2288                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2289                         if (knownSoneId == null) {
2290                                 break;
2291                         }
2292                         synchronized (newSones) {
2293                                 knownSones.add(knownSoneId);
2294                         }
2295                 }
2296
2297                 /* load known posts. */
2298                 int postCounter = 0;
2299                 while (true) {
2300                         String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2301                         if (knownPostId == null) {
2302                                 break;
2303                         }
2304                         synchronized (newPosts) {
2305                                 knownPosts.add(knownPostId);
2306                         }
2307                 }
2308
2309                 /* load known replies. */
2310                 int replyCounter = 0;
2311                 while (true) {
2312                         String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2313                         if (knownReplyId == null) {
2314                                 break;
2315                         }
2316                         synchronized (newReplies) {
2317                                 knownReplies.add(knownReplyId);
2318                         }
2319                 }
2320
2321                 /* load bookmarked posts. */
2322                 int bookmarkedPostCounter = 0;
2323                 while (true) {
2324                         String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2325                         if (bookmarkedPostId == null) {
2326                                 break;
2327                         }
2328                         synchronized (bookmarkedPosts) {
2329                                 bookmarkedPosts.add(bookmarkedPostId);
2330                         }
2331                 }
2332
2333         }
2334
2335         /**
2336          * Loads an {@link Integer} configuration value for the option with the
2337          * given name, logging validation failures.
2338          *
2339          * @param optionName
2340          *            The name of the option to load
2341          */
2342         private void loadConfigurationValue(String optionName) {
2343                 try {
2344                         options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2345                 } catch (IllegalArgumentException iae1) {
2346                         logger.log(Level.WARNING, "Invalid value for " + optionName + " in configuration, using default.");
2347                 }
2348         }
2349
2350         /**
2351          * Generate a Sone URI from the given URI and latest edition.
2352          *
2353          * @param uriString
2354          *            The URI to derive the Sone URI from
2355          * @return The derived URI
2356          */
2357         private FreenetURI getSoneUri(String uriString) {
2358                 try {
2359                         FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2360                         return uri;
2361                 } catch (MalformedURLException mue1) {
2362                         logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
2363                         return null;
2364                 }
2365         }
2366
2367         //
2368         // INTERFACE IdentityListener
2369         //
2370
2371         /**
2372          * {@inheritDoc}
2373          */
2374         @Override
2375         public void ownIdentityAdded(OwnIdentity ownIdentity) {
2376                 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
2377                 if (ownIdentity.hasContext("Sone")) {
2378                         trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2379                         addLocalSone(ownIdentity);
2380                 }
2381         }
2382
2383         /**
2384          * {@inheritDoc}
2385          */
2386         @Override
2387         public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2388                 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
2389                 trustedIdentities.remove(ownIdentity);
2390         }
2391
2392         /**
2393          * {@inheritDoc}
2394          */
2395         @Override
2396         public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2397                 logger.log(Level.FINEST, "Adding Identity: " + identity);
2398                 trustedIdentities.get(ownIdentity).add(identity);
2399                 addRemoteSone(identity);
2400         }
2401
2402         /**
2403          * {@inheritDoc}
2404          */
2405         @Override
2406         public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2407                 new Thread(new Runnable() {
2408
2409                         @Override
2410                         @SuppressWarnings("synthetic-access")
2411                         public void run() {
2412                                 Sone sone = getRemoteSone(identity.getId());
2413                                 sone.setIdentity(identity);
2414                                 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2415                                 soneDownloader.addSone(sone);
2416                                 soneDownloader.fetchSone(sone);
2417                         }
2418                 }).start();
2419         }
2420
2421         /**
2422          * {@inheritDoc}
2423          */
2424         @Override
2425         public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2426                 trustedIdentities.get(ownIdentity).remove(identity);
2427                 boolean foundIdentity = false;
2428                 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2429                         if (trustedIdentity.getKey().equals(ownIdentity)) {
2430                                 continue;
2431                         }
2432                         if (trustedIdentity.getValue().contains(identity)) {
2433                                 foundIdentity = true;
2434                         }
2435                 }
2436                 if (foundIdentity) {
2437                         /* some local identity still trusts this identity, don’t remove. */
2438                         return;
2439                 }
2440                 Sone sone = getSone(identity.getId(), false);
2441                 if (sone == null) {
2442                         /* TODO - we don’t have the Sone anymore. should this happen? */
2443                         return;
2444                 }
2445                 synchronized (posts) {
2446                         synchronized (newPosts) {
2447                                 for (Post post : sone.getPosts()) {
2448                                         posts.remove(post.getId());
2449                                         newPosts.remove(post.getId());
2450                                         coreListenerManager.firePostRemoved(post);
2451                                 }
2452                         }
2453                 }
2454                 synchronized (replies) {
2455                         synchronized (newReplies) {
2456                                 for (Reply reply : sone.getReplies()) {
2457                                         replies.remove(reply.getId());
2458                                         newReplies.remove(reply.getId());
2459                                         coreListenerManager.fireReplyRemoved(reply);
2460                                 }
2461                         }
2462                 }
2463                 synchronized (remoteSones) {
2464                         remoteSones.remove(identity.getId());
2465                 }
2466                 synchronized (newSones) {
2467                         newSones.remove(identity.getId());
2468                         coreListenerManager.fireSoneRemoved(sone);
2469                 }
2470         }
2471
2472         //
2473         // INTERFACE UpdateListener
2474         //
2475
2476         /**
2477          * {@inheritDoc}
2478          */
2479         @Override
2480         public void updateFound(Version version, long releaseTime, long latestEdition) {
2481                 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2482         }
2483
2484         //
2485         // INTERFACE ImageInsertListener
2486         //
2487
2488         /**
2489          * {@inheritDoc}
2490          */
2491         @Override
2492         public void insertStarted(Sone sone) {
2493                 coreListenerManager.fireSoneInserting(sone);
2494         }
2495
2496         /**
2497          * {@inheritDoc}
2498          */
2499         @Override
2500         public void insertFinished(Sone sone, long insertDuration) {
2501                 coreListenerManager.fireSoneInserted(sone, insertDuration);
2502         }
2503
2504         /**
2505          * {@inheritDoc}
2506          */
2507         @Override
2508         public void insertAborted(Sone sone, Throwable cause) {
2509                 coreListenerManager.fireSoneInsertAborted(sone, cause);
2510         }
2511
2512         //
2513         // SONEINSERTLISTENER METHODS
2514         //
2515
2516         /**
2517          * {@inheritDoc}
2518          */
2519         @Override
2520         public void imageInsertStarted(Image image) {
2521                 logger.log(Level.WARNING, "Image insert started for " + image);
2522                 coreListenerManager.fireImageInsertStarted(image);
2523         }
2524
2525         /**
2526          * {@inheritDoc}
2527          */
2528         @Override
2529         public void imageInsertAborted(Image image) {
2530                 logger.log(Level.WARNING, "Image insert aborted for " + image);
2531                 coreListenerManager.fireImageInsertAborted(image);
2532         }
2533
2534         /**
2535          * {@inheritDoc}
2536          */
2537         @Override
2538         public void imageInsertFinished(Image image, FreenetURI key) {
2539                 logger.log(Level.WARNING, "Image insert finished for " + image + ": " + key);
2540                 image.setKey(key.toString());
2541                 deleteTemporaryImage(image.getId());
2542                 saveSone(image.getSone());
2543                 coreListenerManager.fireImageInsertFinished(image);
2544         }
2545
2546         /**
2547          * {@inheritDoc}
2548          */
2549         @Override
2550         public void imageInsertFailed(Image image, Throwable cause) {
2551                 logger.log(Level.WARNING, "Image insert failed for " + image, cause);
2552                 coreListenerManager.fireImageInsertFailed(image, cause);
2553         }
2554
2555         /**
2556          * Convenience interface for external classes that want to access the core’s
2557          * configuration.
2558          *
2559          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2560          */
2561         public static class Preferences {
2562
2563                 /** The wrapped options. */
2564                 private final Options options;
2565
2566                 /**
2567                  * Creates a new preferences object wrapped around the given options.
2568                  *
2569                  * @param options
2570                  *            The options to wrap
2571                  */
2572                 public Preferences(Options options) {
2573                         this.options = options;
2574                 }
2575
2576                 /**
2577                  * Returns the insertion delay.
2578                  *
2579                  * @return The insertion delay
2580                  */
2581                 public int getInsertionDelay() {
2582                         return options.getIntegerOption("InsertionDelay").get();
2583                 }
2584
2585                 /**
2586                  * Validates the given insertion delay.
2587                  *
2588                  * @param insertionDelay
2589                  *            The insertion delay to validate
2590                  * @return {@code true} if the given insertion delay was valid, {@code
2591                  *         false} otherwise
2592                  */
2593                 public boolean validateInsertionDelay(Integer insertionDelay) {
2594                         return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2595                 }
2596
2597                 /**
2598                  * Sets the insertion delay
2599                  *
2600                  * @param insertionDelay
2601                  *            The new insertion delay, or {@code null} to restore it to
2602                  *            the default value
2603                  * @return This preferences
2604                  */
2605                 public Preferences setInsertionDelay(Integer insertionDelay) {
2606                         options.getIntegerOption("InsertionDelay").set(insertionDelay);
2607                         return this;
2608                 }
2609
2610                 /**
2611                  * Returns the number of posts to show per page.
2612                  *
2613                  * @return The number of posts to show per page
2614                  */
2615                 public int getPostsPerPage() {
2616                         return options.getIntegerOption("PostsPerPage").get();
2617                 }
2618
2619                 /**
2620                  * Validates the number of posts per page.
2621                  *
2622                  * @param postsPerPage
2623                  *            The number of posts per page
2624                  * @return {@code true} if the number of posts per page was valid,
2625                  *         {@code false} otherwise
2626                  */
2627                 public boolean validatePostsPerPage(Integer postsPerPage) {
2628                         return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2629                 }
2630
2631                 /**
2632                  * Sets the number of posts to show per page.
2633                  *
2634                  * @param postsPerPage
2635                  *            The number of posts to show per page
2636                  * @return This preferences object
2637                  */
2638                 public Preferences setPostsPerPage(Integer postsPerPage) {
2639                         options.getIntegerOption("PostsPerPage").set(postsPerPage);
2640                         return this;
2641                 }
2642
2643                 /**
2644                  * Returns the number of characters per post, or <code>-1</code> if the
2645                  * posts should not be cut off.
2646                  *
2647                  * @return The numbers of characters per post
2648                  */
2649                 public int getCharactersPerPost() {
2650                         return options.getIntegerOption("CharactersPerPost").get();
2651                 }
2652
2653                 /**
2654                  * Validates the number of characters per post.
2655                  *
2656                  * @param charactersPerPost
2657                  *            The number of characters per post
2658                  * @return {@code true} if the number of characters per post was valid,
2659                  *         {@code false} otherwise
2660                  */
2661                 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2662                         return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2663                 }
2664
2665                 /**
2666                  * Sets the number of characters per post.
2667                  *
2668                  * @param charactersPerPost
2669                  *            The number of characters per post, or <code>-1</code> to
2670                  *            not cut off the posts
2671                  * @return This preferences objects
2672                  */
2673                 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2674                         options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2675                         return this;
2676                 }
2677
2678                 /**
2679                  * Returns whether Sone requires full access to be even visible.
2680                  *
2681                  * @return {@code true} if Sone requires full access, {@code false}
2682                  *         otherwise
2683                  */
2684                 public boolean isRequireFullAccess() {
2685                         return options.getBooleanOption("RequireFullAccess").get();
2686                 }
2687
2688                 /**
2689                  * Sets whether Sone requires full access to be even visible.
2690                  *
2691                  * @param requireFullAccess
2692                  *            {@code true} if Sone requires full access, {@code false}
2693                  *            otherwise
2694                  */
2695                 public void setRequireFullAccess(Boolean requireFullAccess) {
2696                         options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2697                 }
2698
2699                 /**
2700                  * Returns the positive trust.
2701                  *
2702                  * @return The positive trust
2703                  */
2704                 public int getPositiveTrust() {
2705                         return options.getIntegerOption("PositiveTrust").get();
2706                 }
2707
2708                 /**
2709                  * Validates the positive trust.
2710                  *
2711                  * @param positiveTrust
2712                  *            The positive trust to validate
2713                  * @return {@code true} if the positive trust was valid, {@code false}
2714                  *         otherwise
2715                  */
2716                 public boolean validatePositiveTrust(Integer positiveTrust) {
2717                         return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2718                 }
2719
2720                 /**
2721                  * Sets the positive trust.
2722                  *
2723                  * @param positiveTrust
2724                  *            The new positive trust, or {@code null} to restore it to
2725                  *            the default vlaue
2726                  * @return This preferences
2727                  */
2728                 public Preferences setPositiveTrust(Integer positiveTrust) {
2729                         options.getIntegerOption("PositiveTrust").set(positiveTrust);
2730                         return this;
2731                 }
2732
2733                 /**
2734                  * Returns the negative trust.
2735                  *
2736                  * @return The negative trust
2737                  */
2738                 public int getNegativeTrust() {
2739                         return options.getIntegerOption("NegativeTrust").get();
2740                 }
2741
2742                 /**
2743                  * Validates the negative trust.
2744                  *
2745                  * @param negativeTrust
2746                  *            The negative trust to validate
2747                  * @return {@code true} if the negative trust was valid, {@code false}
2748                  *         otherwise
2749                  */
2750                 public boolean validateNegativeTrust(Integer negativeTrust) {
2751                         return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2752                 }
2753
2754                 /**
2755                  * Sets the negative trust.
2756                  *
2757                  * @param negativeTrust
2758                  *            The negative trust, or {@code null} to restore it to the
2759                  *            default value
2760                  * @return The preferences
2761                  */
2762                 public Preferences setNegativeTrust(Integer negativeTrust) {
2763                         options.getIntegerOption("NegativeTrust").set(negativeTrust);
2764                         return this;
2765                 }
2766
2767                 /**
2768                  * Returns the trust comment. This is the comment that is set in the web
2769                  * of trust when a trust value is assigned to an identity.
2770                  *
2771                  * @return The trust comment
2772                  */
2773                 public String getTrustComment() {
2774                         return options.getStringOption("TrustComment").get();
2775                 }
2776
2777                 /**
2778                  * Sets the trust comment.
2779                  *
2780                  * @param trustComment
2781                  *            The trust comment, or {@code null} to restore it to the
2782                  *            default value
2783                  * @return This preferences
2784                  */
2785                 public Preferences setTrustComment(String trustComment) {
2786                         options.getStringOption("TrustComment").set(trustComment);
2787                         return this;
2788                 }
2789
2790                 /**
2791                  * Returns whether the {@link FcpInterface FCP interface} is currently
2792                  * active.
2793                  *
2794                  * @see FcpInterface#setActive(boolean)
2795                  * @return {@code true} if the FCP interface is currently active,
2796                  *         {@code false} otherwise
2797                  */
2798                 public boolean isFcpInterfaceActive() {
2799                         return options.getBooleanOption("ActivateFcpInterface").get();
2800                 }
2801
2802                 /**
2803                  * Sets whether the {@link FcpInterface FCP interface} is currently
2804                  * active.
2805                  *
2806                  * @see FcpInterface#setActive(boolean)
2807                  * @param fcpInterfaceActive
2808                  *            {@code true} to activate the FCP interface, {@code false}
2809                  *            to deactivate the FCP interface
2810                  * @return This preferences object
2811                  */
2812                 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2813                         options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2814                         return this;
2815                 }
2816
2817                 /**
2818                  * Returns the action level for which full access to the FCP interface
2819                  * is required.
2820                  *
2821                  * @return The action level for which full access to the FCP interface
2822                  *         is required
2823                  */
2824                 public FullAccessRequired getFcpFullAccessRequired() {
2825                         return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2826                 }
2827
2828                 /**
2829                  * Sets the action level for which full access to the FCP interface is
2830                  * required
2831                  *
2832                  * @param fcpFullAccessRequired
2833                  *            The action level
2834                  * @return This preferences
2835                  */
2836                 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2837                         options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);
2838                         return this;
2839                 }
2840
2841                 /**
2842                  * Returns whether Sone should clear its settings on the next restart.
2843                  * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
2844                  * to return {@code true} as well!
2845                  *
2846                  * @return {@code true} if Sone should clear its settings on the next
2847                  *         restart, {@code false} otherwise
2848                  */
2849                 public boolean isClearOnNextRestart() {
2850                         return options.getBooleanOption("ClearOnNextRestart").get();
2851                 }
2852
2853                 /**
2854                  * Sets whether Sone will clear its settings on the next restart.
2855                  *
2856                  * @param clearOnNextRestart
2857                  *            {@code true} if Sone should clear its settings on the next
2858                  *            restart, {@code false} otherwise
2859                  * @return This preferences
2860                  */
2861                 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2862                         options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2863                         return this;
2864                 }
2865
2866                 /**
2867                  * Returns whether Sone should really clear its settings on next
2868                  * restart. This is a confirmation option that needs to be set in
2869                  * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
2870                  * settings on the next restart.
2871                  *
2872                  * @return {@code true} if Sone should really clear its settings on the
2873                  *         next restart, {@code false} otherwise
2874                  */
2875                 public boolean isReallyClearOnNextRestart() {
2876                         return options.getBooleanOption("ReallyClearOnNextRestart").get();
2877                 }
2878
2879                 /**
2880                  * Sets whether Sone should really clear its settings on the next
2881                  * restart.
2882                  *
2883                  * @param reallyClearOnNextRestart
2884                  *            {@code true} if Sone should really clear its settings on
2885                  *            the next restart, {@code false} otherwise
2886                  * @return This preferences
2887                  */
2888                 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2889                         options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);
2890                         return this;
2891                 }
2892
2893         }
2894
2895 }