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