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