Suppress some warnings about variables hiding other variables.
[Sone.git] / src / main / java / net / pterodactylus / sone / 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                         @SuppressWarnings("hiding")
182                         Map<String, OwnIdentity> currentOwnIdentities = new HashMap<String, OwnIdentity>();
183
184                         Set<OwnIdentity> ownIdentities = null;
185                         boolean identitiesLoaded = false;
186                         try {
187                                 /* get all identities with the wanted context from WoT. */
188                                 ownIdentities = webOfTrustConnector.loadAllOwnIdentities();
189
190                                 /* load trusted identities. */
191                                 for (OwnIdentity ownIdentity : ownIdentities) {
192                                         if ((context != null) && !ownIdentity.hasContext(context)) {
193                                                 continue;
194                                         }
195                                         currentOwnIdentities.put(ownIdentity.getId(), ownIdentity);
196
197                                         Set<Identity> trustedIdentities = webOfTrustConnector.loadTrustedIdentities(ownIdentity, context);
198                                         Map<String, Identity> identities = new HashMap<String, Identity>();
199                                         currentIdentities.put(ownIdentity, identities);
200                                         for (Identity identity : trustedIdentities) {
201                                                 identities.put(identity.getId(), identity);
202                                         }
203                                 }
204                                 identitiesLoaded = true;
205                         } catch (WebOfTrustException wote1) {
206                                 logger.log(Level.WARNING, "WoT has disappeared!", wote1);
207                         }
208
209                         if (identitiesLoaded) {
210
211                                 /* check for changes. */
212                                 checkOwnIdentities(currentOwnIdentities);
213
214                                 /* now check for changes in remote identities. */
215                                 for (OwnIdentity ownIdentity : currentOwnIdentities.values()) {
216
217                                         /* find new identities. */
218                                         for (Identity currentIdentity : currentIdentities.get(ownIdentity).values()) {
219                                                 if (!oldIdentities.containsKey(ownIdentity) || !oldIdentities.get(ownIdentity).containsKey(currentIdentity.getId())) {
220                                                         identityListenerManager.fireIdentityAdded(ownIdentity, currentIdentity);
221                                                 }
222                                         }
223
224                                         /* find removed identities. */
225                                         if (oldIdentities.containsKey(ownIdentity)) {
226                                                 for (Identity oldIdentity : oldIdentities.get(ownIdentity).values()) {
227                                                         if (!currentIdentities.get(ownIdentity).containsKey(oldIdentity.getId())) {
228                                                                 identityListenerManager.fireIdentityRemoved(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                                                                 identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
242                                                                 continue;
243                                                         }
244                                                         for (String oldContext : oldContexts) {
245                                                                 if (!newContexts.contains(oldContext)) {
246                                                                         identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
247                                                                         break;
248                                                                 }
249                                                         }
250                                                 }
251
252                                                 /* check for changes in the properties. */
253                                                 for (Identity oldIdentity : oldIdentities.get(ownIdentity).values()) {
254                                                         if (!currentIdentities.get(ownIdentity).containsKey(oldIdentity.getId())) {
255                                                                 continue;
256                                                         }
257                                                         Identity newIdentity = currentIdentities.get(ownIdentity).get(oldIdentity.getId());
258                                                         Map<String, String> oldProperties = oldIdentity.getProperties();
259                                                         Map<String, String> newProperties = newIdentity.getProperties();
260                                                         if (oldProperties.size() != newProperties.size()) {
261                                                                 identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
262                                                                 continue;
263                                                         }
264                                                         for (Entry<String, String> oldProperty : oldProperties.entrySet()) {
265                                                                 if (!newProperties.containsKey(oldProperty.getKey()) || !newProperties.get(oldProperty.getKey()).equals(oldProperty.getValue())) {
266                                                                         identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
267                                                                         break;
268                                                                 }
269                                                         }
270                                                 }
271                                         }
272                                 }
273
274                                 /* remember the current set of identities. */
275                                 oldIdentities = currentIdentities;
276                         }
277
278                         /* wait a minute before checking again. */
279                         sleep(60 * 1000);
280                 }
281         }
282
283         //
284         // PRIVATE METHODS
285         //
286
287         /**
288          * Checks the given new list of own identities for added or removed own
289          * identities, as compared to {@link #currentOwnIdentities}.
290          *
291          * @param newOwnIdentities
292          *            The new own identities
293          */
294         private void checkOwnIdentities(Map<String, OwnIdentity> newOwnIdentities) {
295                 synchronized (syncObject) {
296
297                         /* find removed own identities: */
298                         for (OwnIdentity oldOwnIdentity : currentOwnIdentities.values()) {
299                                 if (!newOwnIdentities.containsKey(oldOwnIdentity.getId())) {
300                                         identityListenerManager.fireOwnIdentityRemoved(oldOwnIdentity);
301                                 }
302                         }
303
304                         /* find added own identities. */
305                         for (OwnIdentity currentOwnIdentity : newOwnIdentities.values()) {
306                                 if (!currentOwnIdentities.containsKey(currentOwnIdentity.getId())) {
307                                         identityListenerManager.fireOwnIdentityAdded(currentOwnIdentity);
308                                 }
309                         }
310
311                         currentOwnIdentities.clear();
312                         currentOwnIdentities.putAll(newOwnIdentities);
313                 }
314         }
315
316 }