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