Prevent exception if own identity does not have the correct context.
[WoTNS.git] / src / main / java / net / pterodactylus / wotns / freenet / wot / IdentityManager.java
1 /*
2  * Sone - IdentityManager.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.wotns.freenet.wot;
19
20 import java.util.Collections;
21 import java.util.HashMap;
22 import java.util.HashSet;
23 import java.util.Map;
24 import java.util.Set;
25 import java.util.Map.Entry;
26 import java.util.logging.Level;
27 import java.util.logging.Logger;
28
29 import net.pterodactylus.util.collection.SetBuilder;
30 import net.pterodactylus.util.logging.Logging;
31 import net.pterodactylus.util.object.Default;
32 import net.pterodactylus.util.service.AbstractService;
33 import net.pterodactylus.wotns.freenet.plugin.PluginException;
34
35 /**
36  * The identity manager takes care of loading and storing identities, their
37  * contexts, and properties. It does so in a way that does not expose errors via
38  * exceptions but it only logs them and tries to return sensible defaults.
39  * <p>
40  * It is also responsible for polling identities from the Web of Trust plugin
41  * and notifying registered {@link IdentityListener}s when {@link Identity}s and
42  * {@link OwnIdentity}s are discovered or disappearing.
43  *
44  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
45  */
46 public class IdentityManager extends AbstractService {
47
48         /** Object used for synchronization. */
49         private final Object syncObject = new Object() {
50                 /* inner class for better lock names. */
51         };
52
53         /** The logger. */
54         private static final Logger logger = Logging.getLogger(IdentityManager.class);
55
56         /** The event manager. */
57         private final IdentityListenerManager identityListenerManager = new IdentityListenerManager();
58
59         /** The Web of Trust connector. */
60         private final WebOfTrustConnector webOfTrustConnector;
61
62         /** The context to filter for. */
63         private volatile String context;
64
65         /** The currently known own identities. */
66         /* synchronize access on syncObject. */
67         private Map<String, OwnIdentity> currentOwnIdentities = new HashMap<String, OwnIdentity>();
68
69         /** The currently trusted identities. */
70         private Map<OwnIdentity, Set<Identity>> currentTrustedIdentities = new HashMap<OwnIdentity, Set<Identity>>();
71
72         /**
73          * Creates a new identity manager.
74          *
75          * @param webOfTrustConnector
76          *            The Web of Trust connector
77          */
78         public IdentityManager(WebOfTrustConnector webOfTrustConnector) {
79                 super("Sone Identity Manager", false);
80                 this.webOfTrustConnector = webOfTrustConnector;
81         }
82
83         //
84         // LISTENER MANAGEMENT
85         //
86
87         /**
88          * Adds a listener for identity events.
89          *
90          * @param identityListener
91          *            The listener to add
92          */
93         public void addIdentityListener(IdentityListener identityListener) {
94                 identityListenerManager.addListener(identityListener);
95         }
96
97         /**
98          * Removes a listener for identity events.
99          *
100          * @param identityListener
101          *            The listener to remove
102          */
103         public void removeIdentityListener(IdentityListener identityListener) {
104                 identityListenerManager.removeListener(identityListener);
105         }
106
107         //
108         // ACCESSORS
109         //
110
111         /**
112          * Sets the context to filter own identities and trusted identities for.
113          *
114          * @param context
115          *            The context to filter for, or {@code null} to not filter
116          */
117         public void setContext(String context) {
118                 this.context = context;
119         }
120
121         /**
122          * Returns whether the Web of Trust plugin could be reached during the last
123          * try.
124          *
125          * @return {@code true} if the Web of Trust plugin is connected, {@code
126          *         false} otherwise
127          */
128         public boolean isConnected() {
129                 try {
130                         webOfTrustConnector.ping();
131                         return true;
132                 } catch (PluginException pe1) {
133                         /* not connected, ignore. */
134                         return false;
135                 }
136         }
137
138         /**
139          * Returns the own identity with the given ID.
140          *
141          * @param id
142          *            The ID of the own identity
143          * @return The own identity, or {@code null} if there is no such identity
144          */
145         public OwnIdentity getOwnIdentity(String id) {
146                 Set<OwnIdentity> allOwnIdentities = getAllOwnIdentities();
147                 for (OwnIdentity ownIdentity : allOwnIdentities) {
148                         if (ownIdentity.getId().equals(id)) {
149                                 return ownIdentity;
150                         }
151                 }
152                 return null;
153         }
154
155         /**
156          * Returns all own identities.
157          *
158          * @return All own identities
159          */
160         public Set<OwnIdentity> getAllOwnIdentities() {
161                 try {
162                         Set<OwnIdentity> ownIdentities = webOfTrustConnector.loadAllOwnIdentities();
163                         Map<String, OwnIdentity> newOwnIdentities = new HashMap<String, OwnIdentity>();
164                         for (OwnIdentity ownIdentity : ownIdentities) {
165                                 newOwnIdentities.put(ownIdentity.getId(), ownIdentity);
166                         }
167                         checkOwnIdentities(newOwnIdentities);
168                         return ownIdentities;
169                 } catch (WebOfTrustException wote1) {
170                         logger.log(Level.WARNING, "Could not load all own identities!", wote1);
171                         return Collections.emptySet();
172                 }
173         }
174
175         public Set<Identity> getTrustedIdentities(OwnIdentity ownIdentity) {
176                 SetBuilder<Identity> identities = new SetBuilder<Identity>();
177                 if ((context == null) || ownIdentity.getContexts().contains(context)) {
178                         identities.add(ownIdentity);
179                 }
180                 synchronized (syncObject) {
181                         identities.addAll(Default.forNull(currentTrustedIdentities.get(ownIdentity), Collections.<Identity> emptySet()));
182                 }
183                 return identities.get();
184         }
185
186         //
187         // SERVICE METHODS
188         //
189
190         /**
191          * {@inheritDoc}
192          */
193         @Override
194         protected void serviceRun() {
195                 Map<OwnIdentity, Map<String, Identity>> oldIdentities = Collections.emptyMap();
196                 while (!shouldStop()) {
197                         Map<OwnIdentity, Map<String, Identity>> currentIdentities = new HashMap<OwnIdentity, Map<String, Identity>>();
198                         @SuppressWarnings("hiding")
199                         Map<String, OwnIdentity> currentOwnIdentities = new HashMap<String, OwnIdentity>();
200
201                         Set<OwnIdentity> ownIdentities = null;
202                         boolean identitiesLoaded = false;
203                         try {
204                                 /* get all identities with the wanted context from WoT. */
205                                 ownIdentities = webOfTrustConnector.loadAllOwnIdentities();
206
207                                 /* load trusted identities. */
208                                 for (OwnIdentity ownIdentity : ownIdentities) {
209                                         if ((context != null) && !ownIdentity.hasContext(context)) {
210                                                 continue;
211                                         }
212                                         currentOwnIdentities.put(ownIdentity.getId(), ownIdentity);
213
214                                         Set<Identity> trustedIdentities = webOfTrustConnector.loadTrustedIdentities(ownIdentity, context);
215                                         Map<String, Identity> identities = new HashMap<String, Identity>();
216                                         currentIdentities.put(ownIdentity, identities);
217                                         for (Identity identity : trustedIdentities) {
218                                                 identities.put(identity.getId(), identity);
219                                         }
220                                 }
221                                 identitiesLoaded = true;
222                         } catch (WebOfTrustException wote1) {
223                                 logger.log(Level.WARNING, "WoT has disappeared!", wote1);
224                         }
225
226                         if (identitiesLoaded) {
227
228                                 /* check for changes. */
229                                 checkOwnIdentities(currentOwnIdentities);
230
231                                 /* now check for changes in remote identities. */
232                                 for (OwnIdentity ownIdentity : currentOwnIdentities.values()) {
233
234                                         /* find new identities. */
235                                         for (Identity currentIdentity : currentIdentities.get(ownIdentity).values()) {
236                                                 if (!oldIdentities.containsKey(ownIdentity) || !oldIdentities.get(ownIdentity).containsKey(currentIdentity.getId())) {
237                                                         identityListenerManager.fireIdentityAdded(ownIdentity, currentIdentity);
238                                                 }
239                                         }
240
241                                         /* find removed identities. */
242                                         if (oldIdentities.containsKey(ownIdentity)) {
243                                                 for (Identity oldIdentity : oldIdentities.get(ownIdentity).values()) {
244                                                         if (!currentIdentities.get(ownIdentity).containsKey(oldIdentity.getId())) {
245                                                                 identityListenerManager.fireIdentityRemoved(ownIdentity, oldIdentity);
246                                                         }
247                                                 }
248
249                                                 /* check for changes in the contexts. */
250                                                 for (Identity oldIdentity : oldIdentities.get(ownIdentity).values()) {
251                                                         if (!currentIdentities.get(ownIdentity).containsKey(oldIdentity.getId())) {
252                                                                 continue;
253                                                         }
254                                                         Identity newIdentity = currentIdentities.get(ownIdentity).get(oldIdentity.getId());
255                                                         Set<String> oldContexts = oldIdentity.getContexts();
256                                                         Set<String> newContexts = newIdentity.getContexts();
257                                                         if (oldContexts.size() != newContexts.size()) {
258                                                                 identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
259                                                                 continue;
260                                                         }
261                                                         for (String oldContext : oldContexts) {
262                                                                 if (!newContexts.contains(oldContext)) {
263                                                                         identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
264                                                                         break;
265                                                                 }
266                                                         }
267                                                 }
268
269                                                 /* check for changes in the properties. */
270                                                 for (Identity oldIdentity : oldIdentities.get(ownIdentity).values()) {
271                                                         if (!currentIdentities.get(ownIdentity).containsKey(oldIdentity.getId())) {
272                                                                 continue;
273                                                         }
274                                                         Identity newIdentity = currentIdentities.get(ownIdentity).get(oldIdentity.getId());
275                                                         Map<String, String> oldProperties = oldIdentity.getProperties();
276                                                         Map<String, String> newProperties = newIdentity.getProperties();
277                                                         if (oldProperties.size() != newProperties.size()) {
278                                                                 identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
279                                                                 continue;
280                                                         }
281                                                         for (Entry<String, String> oldProperty : oldProperties.entrySet()) {
282                                                                 if (!newProperties.containsKey(oldProperty.getKey()) || !newProperties.get(oldProperty.getKey()).equals(oldProperty.getValue())) {
283                                                                         identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
284                                                                         break;
285                                                                 }
286                                                         }
287                                                 }
288                                         }
289                                 }
290
291                                 /* remember the current set of identities. */
292                                 oldIdentities = currentIdentities;
293                                 synchronized (syncObject) {
294                                         currentTrustedIdentities.clear();
295                                         for (Entry<OwnIdentity, Map<String, Identity>> entry : currentIdentities.entrySet()) {
296                                                 Set<Identity> identities = new HashSet<Identity>();
297                                                 currentTrustedIdentities.put(entry.getKey(), identities);
298                                                 for (Identity identity : entry.getValue().values()) {
299                                                         identities.add(identity);
300                                                 }
301                                         }
302                                 }
303                         }
304
305                         /* wait a minute before checking again. */
306                         sleep(60 * 1000);
307                 }
308         }
309
310         //
311         // PRIVATE METHODS
312         //
313
314         /**
315          * Checks the given new list of own identities for added or removed own
316          * identities, as compared to {@link #currentOwnIdentities}.
317          *
318          * @param newOwnIdentities
319          *            The new own identities
320          */
321         private void checkOwnIdentities(Map<String, OwnIdentity> newOwnIdentities) {
322                 synchronized (syncObject) {
323
324                         /* find removed own identities: */
325                         for (OwnIdentity oldOwnIdentity : currentOwnIdentities.values()) {
326                                 if (!newOwnIdentities.containsKey(oldOwnIdentity.getId())) {
327                                         identityListenerManager.fireOwnIdentityRemoved(oldOwnIdentity);
328                                 }
329                         }
330
331                         /* find added own identities. */
332                         for (OwnIdentity currentOwnIdentity : newOwnIdentities.values()) {
333                                 if (!currentOwnIdentities.containsKey(currentOwnIdentity.getId())) {
334                                         identityListenerManager.fireOwnIdentityAdded(currentOwnIdentity);
335                                 }
336                         }
337
338                         currentOwnIdentities.clear();
339                         currentOwnIdentities.putAll(newOwnIdentities);
340                 }
341         }
342
343 }