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