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