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