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