3c3c9f9221cc64e8e0c7276fe80cfb07a80a0df6
[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.HashSet;
23 import java.util.Map;
24 import java.util.Map.Entry;
25 import java.util.Set;
26 import java.util.logging.Level;
27 import java.util.logging.Logger;
28
29 import net.pterodactylus.sone.freenet.plugin.PluginException;
30 import net.pterodactylus.util.logging.Logging;
31 import net.pterodactylus.util.service.AbstractService;
32
33 /**
34  * The identity manager takes care of loading and storing identities, their
35  * contexts, and properties. It does so in a way that does not expose errors via
36  * exceptions but it only logs them and tries to return sensible defaults.
37  * <p>
38  * It is also responsible for polling identities from the Web of Trust plugin
39  * and notifying registered {@link IdentityListener}s when {@link Identity}s and
40  * {@link OwnIdentity}s are discovered or disappearing.
41  *
42  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
43  */
44 public class IdentityManager extends AbstractService {
45
46         /** Object used for synchronization. */
47         @SuppressWarnings("hiding")
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(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                 return new HashSet<OwnIdentity>(currentOwnIdentities.values());
158         }
159
160         //
161         // SERVICE METHODS
162         //
163
164         /**
165          * {@inheritDoc}
166          */
167         @Override
168         protected void serviceRun() {
169                 Map<OwnIdentity, Map<String, Identity>> oldIdentities = Collections.emptyMap();
170                 while (!shouldStop()) {
171                         Map<OwnIdentity, Map<String, Identity>> currentIdentities = new HashMap<OwnIdentity, Map<String, Identity>>();
172                         Map<String, OwnIdentity> currentOwnIdentities = new HashMap<String, OwnIdentity>();
173
174                         Set<OwnIdentity> ownIdentities = null;
175                         boolean identitiesLoaded = false;
176                         try {
177                                 /* get all identities with the wanted context from WoT. */
178                                 ownIdentities = webOfTrustConnector.loadAllOwnIdentities();
179
180                                 /* load trusted identities. */
181                                 for (OwnIdentity ownIdentity : ownIdentities) {
182                                         if ((context != null) && !ownIdentity.hasContext(context)) {
183                                                 continue;
184                                         }
185                                         currentOwnIdentities.put(ownIdentity.getId(), ownIdentity);
186
187                                         Set<Identity> trustedIdentities = webOfTrustConnector.loadTrustedIdentities(ownIdentity, context);
188                                         Map<String, Identity> identities = new HashMap<String, Identity>();
189                                         currentIdentities.put(ownIdentity, identities);
190                                         for (Identity identity : trustedIdentities) {
191                                                 identities.put(identity.getId(), identity);
192                                         }
193                                 }
194                                 identitiesLoaded = true;
195                         } catch (WebOfTrustException wote1) {
196                                 logger.log(Level.WARNING, "WoT has disappeared!", wote1);
197                         }
198
199                         if (identitiesLoaded) {
200
201                                 /* check for changes. */
202                                 checkOwnIdentities(currentOwnIdentities);
203
204                                 /* now check for changes in remote identities. */
205                                 for (OwnIdentity ownIdentity : currentOwnIdentities.values()) {
206
207                                         /* find new identities. */
208                                         for (Identity currentIdentity : currentIdentities.get(ownIdentity).values()) {
209                                                 if (!oldIdentities.containsKey(ownIdentity) || !oldIdentities.get(ownIdentity).containsKey(currentIdentity.getId())) {
210                                                         identityListenerManager.fireIdentityAdded(ownIdentity, currentIdentity);
211                                                 }
212                                         }
213
214                                         /* find removed identities. */
215                                         if (oldIdentities.containsKey(ownIdentity)) {
216                                                 for (Identity oldIdentity : oldIdentities.get(ownIdentity).values()) {
217                                                         if (!currentIdentities.get(ownIdentity).containsKey(oldIdentity.getId())) {
218                                                                 identityListenerManager.fireIdentityRemoved(ownIdentity, oldIdentity);
219                                                         }
220                                                 }
221
222                                                 /* check for changes in the contexts. */
223                                                 for (Identity oldIdentity : oldIdentities.get(ownIdentity).values()) {
224                                                         if (!currentIdentities.get(ownIdentity).containsKey(oldIdentity.getId())) {
225                                                                 continue;
226                                                         }
227                                                         Identity newIdentity = currentIdentities.get(ownIdentity).get(oldIdentity.getId());
228                                                         Set<String> oldContexts = oldIdentity.getContexts();
229                                                         Set<String> newContexts = newIdentity.getContexts();
230                                                         if (oldContexts.size() != newContexts.size()) {
231                                                                 identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
232                                                                 continue;
233                                                         }
234                                                         for (String oldContext : oldContexts) {
235                                                                 if (!newContexts.contains(oldContext)) {
236                                                                         identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
237                                                                         break;
238                                                                 }
239                                                         }
240                                                 }
241
242                                                 /* check for changes in the properties. */
243                                                 for (Identity oldIdentity : oldIdentities.get(ownIdentity).values()) {
244                                                         if (!currentIdentities.get(ownIdentity).containsKey(oldIdentity.getId())) {
245                                                                 continue;
246                                                         }
247                                                         Identity newIdentity = currentIdentities.get(ownIdentity).get(oldIdentity.getId());
248                                                         Map<String, String> oldProperties = oldIdentity.getProperties();
249                                                         Map<String, String> newProperties = newIdentity.getProperties();
250                                                         if (oldProperties.size() != newProperties.size()) {
251                                                                 identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
252                                                                 continue;
253                                                         }
254                                                         for (Entry<String, String> oldProperty : oldProperties.entrySet()) {
255                                                                 if (!newProperties.containsKey(oldProperty.getKey()) || !newProperties.get(oldProperty.getKey()).equals(oldProperty.getValue())) {
256                                                                         identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
257                                                                         break;
258                                                                 }
259                                                         }
260                                                 }
261                                         }
262                                 }
263
264                                 /* remember the current set of identities. */
265                                 oldIdentities = currentIdentities;
266                         }
267
268                         /* wait a minute before checking again. */
269                         sleep(60 * 1000);
270                 }
271         }
272
273         //
274         // PRIVATE METHODS
275         //
276
277         /**
278          * Checks the given new list of own identities for added or removed own
279          * identities, as compared to {@link #currentOwnIdentities}.
280          *
281          * @param newOwnIdentities
282          *            The new own identities
283          */
284         private void checkOwnIdentities(Map<String, OwnIdentity> newOwnIdentities) {
285                 synchronized (syncObject) {
286
287                         /* find removed own identities: */
288                         for (OwnIdentity oldOwnIdentity : currentOwnIdentities.values()) {
289                                 OwnIdentity newOwnIdentity = newOwnIdentities.get(oldOwnIdentity.getId());
290                                 if ((newOwnIdentity == null) || ((context != null) && oldOwnIdentity.hasContext(context) && !newOwnIdentity.hasContext(context))) {
291                                         identityListenerManager.fireOwnIdentityRemoved(new DefaultOwnIdentity(oldOwnIdentity));
292                                 }
293                         }
294
295                         /* find added own identities. */
296                         for (OwnIdentity currentOwnIdentity : newOwnIdentities.values()) {
297                                 OwnIdentity oldOwnIdentity = currentOwnIdentities.get(currentOwnIdentity.getId());
298                                 if (((oldOwnIdentity == null) && ((context == null) || currentOwnIdentity.hasContext(context))) || ((oldOwnIdentity != null) && (context != null) && (!oldOwnIdentity.hasContext(context) && currentOwnIdentity.hasContext(context)))) {
299                                         identityListenerManager.fireOwnIdentityAdded(new DefaultOwnIdentity(currentOwnIdentity));
300                                 }
301                         }
302
303                         currentOwnIdentities.clear();
304                         currentOwnIdentities.putAll(newOwnIdentities);
305                 }
306         }
307
308 }