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