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