32c0d27e7ac1cb485ebd6c30e7ccc142a7a7d6cf
[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(webOfTrustConnector, 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                                 @SuppressWarnings("synthetic-access")
172                                 public OwnIdentity map(OwnIdentity input) {
173                                         return new DefaultOwnIdentity(webOfTrustConnector, input);
174                                 }
175                         });
176                 } catch (WebOfTrustException wote1) {
177                         logger.log(Level.WARNING, "Could not load all own identities!", wote1);
178                         return Collections.emptySet();
179                 }
180         }
181
182         //
183         // SERVICE METHODS
184         //
185
186         /**
187          * {@inheritDoc}
188          */
189         @Override
190         protected void serviceRun() {
191                 Map<OwnIdentity, Map<String, Identity>> oldIdentities = Collections.emptyMap();
192                 while (!shouldStop()) {
193                         Map<OwnIdentity, Map<String, Identity>> currentIdentities = new HashMap<OwnIdentity, Map<String, Identity>>();
194                         Map<String, OwnIdentity> currentOwnIdentities = new HashMap<String, OwnIdentity>();
195
196                         Set<OwnIdentity> ownIdentities = null;
197                         boolean identitiesLoaded = false;
198                         try {
199                                 /* get all identities with the wanted context from WoT. */
200                                 ownIdentities = webOfTrustConnector.loadAllOwnIdentities();
201
202                                 /* load trusted identities. */
203                                 for (OwnIdentity ownIdentity : ownIdentities) {
204                                         if ((context != null) && !ownIdentity.hasContext(context)) {
205                                                 continue;
206                                         }
207                                         currentOwnIdentities.put(ownIdentity.getId(), ownIdentity);
208
209                                         Set<Identity> trustedIdentities = webOfTrustConnector.loadTrustedIdentities(ownIdentity, context);
210                                         Map<String, Identity> identities = new HashMap<String, Identity>();
211                                         currentIdentities.put(ownIdentity, identities);
212                                         for (Identity identity : trustedIdentities) {
213                                                 identities.put(identity.getId(), identity);
214                                         }
215                                 }
216                                 identitiesLoaded = true;
217                         } catch (WebOfTrustException wote1) {
218                                 logger.log(Level.WARNING, "WoT has disappeared!", wote1);
219                         }
220
221                         if (identitiesLoaded) {
222
223                                 /* check for changes. */
224                                 checkOwnIdentities(currentOwnIdentities);
225
226                                 /* now check for changes in remote identities. */
227                                 for (OwnIdentity ownIdentity : currentOwnIdentities.values()) {
228
229                                         /* find new identities. */
230                                         for (Identity currentIdentity : currentIdentities.get(ownIdentity).values()) {
231                                                 if (!oldIdentities.containsKey(ownIdentity) || !oldIdentities.get(ownIdentity).containsKey(currentIdentity.getId())) {
232                                                         identityListenerManager.fireIdentityAdded(ownIdentity, currentIdentity);
233                                                 }
234                                         }
235
236                                         /* find removed identities. */
237                                         if (oldIdentities.containsKey(ownIdentity)) {
238                                                 for (Identity oldIdentity : oldIdentities.get(ownIdentity).values()) {
239                                                         if (!currentIdentities.get(ownIdentity).containsKey(oldIdentity.getId())) {
240                                                                 identityListenerManager.fireIdentityRemoved(ownIdentity, oldIdentity);
241                                                         }
242                                                 }
243
244                                                 /* check for changes in the contexts. */
245                                                 for (Identity oldIdentity : oldIdentities.get(ownIdentity).values()) {
246                                                         if (!currentIdentities.get(ownIdentity).containsKey(oldIdentity.getId())) {
247                                                                 continue;
248                                                         }
249                                                         Identity newIdentity = currentIdentities.get(ownIdentity).get(oldIdentity.getId());
250                                                         Set<String> oldContexts = oldIdentity.getContexts();
251                                                         Set<String> newContexts = newIdentity.getContexts();
252                                                         if (oldContexts.size() != newContexts.size()) {
253                                                                 identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
254                                                                 continue;
255                                                         }
256                                                         for (String oldContext : oldContexts) {
257                                                                 if (!newContexts.contains(oldContext)) {
258                                                                         identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
259                                                                         break;
260                                                                 }
261                                                         }
262                                                 }
263
264                                                 /* check for changes in the properties. */
265                                                 for (Identity oldIdentity : oldIdentities.get(ownIdentity).values()) {
266                                                         if (!currentIdentities.get(ownIdentity).containsKey(oldIdentity.getId())) {
267                                                                 continue;
268                                                         }
269                                                         Identity newIdentity = currentIdentities.get(ownIdentity).get(oldIdentity.getId());
270                                                         Map<String, String> oldProperties = oldIdentity.getProperties();
271                                                         Map<String, String> newProperties = newIdentity.getProperties();
272                                                         if (oldProperties.size() != newProperties.size()) {
273                                                                 identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
274                                                                 continue;
275                                                         }
276                                                         for (Entry<String, String> oldProperty : oldProperties.entrySet()) {
277                                                                 if (!newProperties.containsKey(oldProperty.getKey()) || !newProperties.get(oldProperty.getKey()).equals(oldProperty.getValue())) {
278                                                                         identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
279                                                                         break;
280                                                                 }
281                                                         }
282                                                 }
283                                         }
284                                 }
285
286                                 /* remember the current set of identities. */
287                                 oldIdentities = currentIdentities;
288                         }
289
290                         /* wait a minute before checking again. */
291                         sleep(60 * 1000);
292                 }
293         }
294
295         //
296         // PRIVATE METHODS
297         //
298
299         /**
300          * Checks the given new list of own identities for added or removed own
301          * identities, as compared to {@link #currentOwnIdentities}.
302          *
303          * @param newOwnIdentities
304          *            The new own identities
305          */
306         private void checkOwnIdentities(Map<String, OwnIdentity> newOwnIdentities) {
307                 synchronized (syncObject) {
308
309                         /* find removed own identities: */
310                         for (OwnIdentity oldOwnIdentity : currentOwnIdentities.values()) {
311                                 OwnIdentity newOwnIdentity = newOwnIdentities.get(oldOwnIdentity.getId());
312                                 if ((newOwnIdentity == null) || ((context != null) && oldOwnIdentity.hasContext(context) && !newOwnIdentity.hasContext(context))) {
313                                         identityListenerManager.fireOwnIdentityRemoved(new DefaultOwnIdentity(webOfTrustConnector, oldOwnIdentity));
314                                 }
315                         }
316
317                         /* find added own identities. */
318                         for (OwnIdentity currentOwnIdentity : newOwnIdentities.values()) {
319                                 OwnIdentity oldOwnIdentity = currentOwnIdentities.get(currentOwnIdentity.getId());
320                                 if (((oldOwnIdentity == null) && ((context == null) || currentOwnIdentity.hasContext(context))) || ((oldOwnIdentity != null) && (context != null) && (!oldOwnIdentity.hasContext(context) && currentOwnIdentity.hasContext(context)))) {
321                                         identityListenerManager.fireOwnIdentityAdded(new DefaultOwnIdentity(webOfTrustConnector, currentOwnIdentity));
322                                 }
323                         }
324
325                         currentOwnIdentities.clear();
326                         currentOwnIdentities.putAll(newOwnIdentities);
327                 }
328         }
329
330 }