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