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