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