Add stop method that deregisters the plugin listener.
[Sone.git] / src / main / java / net / pterodactylus / sone / freenet / wot / WebOfTrustConnector.java
1 /*
2  * Sone - WebOfTrustConnector.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.HashMap;
21 import java.util.HashSet;
22 import java.util.Map;
23 import java.util.Set;
24 import java.util.logging.Level;
25 import java.util.logging.Logger;
26
27 import net.pterodactylus.sone.freenet.plugin.ConnectorListener;
28 import net.pterodactylus.sone.freenet.plugin.PluginConnector;
29 import net.pterodactylus.sone.freenet.plugin.PluginException;
30 import net.pterodactylus.util.logging.Logging;
31 import freenet.support.SimpleFieldSet;
32 import freenet.support.api.Bucket;
33
34 /**
35  * Connector for the Web of Trust plugin.
36  *
37  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
38  */
39 public class WebOfTrustConnector implements ConnectorListener {
40
41         /** The logger. */
42         private static final Logger logger = Logging.getLogger(WebOfTrustConnector.class);
43
44         /** The name of the WoT plugin. */
45         private static final String WOT_PLUGIN_NAME = "plugins.WebOfTrust.WebOfTrust";
46
47         /** A random connection identifier. */
48         private static final String PLUGIN_CONNECTION_IDENTIFIER = "Sone-WoT-Connector-" + Math.abs(Math.random());
49
50         /** The current reply. */
51         private Reply reply;
52
53         /** The plugin connector. */
54         private final PluginConnector pluginConnector;
55
56         /**
57          * Creates a new Web of Trust connector that uses the given plugin
58          * connector.
59          *
60          * @param pluginConnector
61          *            The plugin connector
62          */
63         public WebOfTrustConnector(PluginConnector pluginConnector) {
64                 this.pluginConnector = pluginConnector;
65                 pluginConnector.addConnectorListener(WOT_PLUGIN_NAME, PLUGIN_CONNECTION_IDENTIFIER, this);
66         }
67
68         //
69         // ACTIONS
70         //
71
72         /**
73          * Stops the web of trust connector.
74          */
75         public void stop() {
76                 pluginConnector.removeConnectorListener(WOT_PLUGIN_NAME, PLUGIN_CONNECTION_IDENTIFIER, this);
77         }
78
79         /**
80          * Loads all own identities from the Web of Trust plugin.
81          *
82          * @return All own identity
83          * @throws WebOfTrustException
84          *             if the own identities can not be loaded
85          */
86         public Set<OwnIdentity> loadAllOwnIdentities() throws WebOfTrustException {
87                 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetOwnIdentities").get());
88                 SimpleFieldSet fields = reply.getFields();
89                 int ownIdentityCounter = -1;
90                 Set<OwnIdentity> ownIdentities = new HashSet<OwnIdentity>();
91                 while (true) {
92                         String id = fields.get("Identity" + ++ownIdentityCounter);
93                         if (id == null) {
94                                 break;
95                         }
96                         String requestUri = fields.get("RequestURI" + ownIdentityCounter);
97                         String insertUri = fields.get("InsertURI" + ownIdentityCounter);
98                         String nickname = fields.get("Nickname" + ownIdentityCounter);
99                         DefaultOwnIdentity ownIdentity = new DefaultOwnIdentity(this, id, nickname, requestUri, insertUri);
100                         ownIdentity.setContextsPrivate(parseContexts("Contexts" + ownIdentityCounter + ".", fields));
101                         ownIdentity.setPropertiesPrivate(parseProperties("Properties" + ownIdentityCounter + ".", fields));
102                         ownIdentities.add(ownIdentity);
103                 }
104                 return ownIdentities;
105         }
106
107         /**
108          * Loads all identities that the given identities trusts with a score of
109          * more than 0.
110          *
111          * @param ownIdentity
112          *            The own identity
113          * @return All trusted identities
114          * @throws PluginException
115          *             if an error occured talking to the Web of Trust plugin
116          */
117         public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity) throws PluginException {
118                 return loadTrustedIdentities(ownIdentity, null);
119         }
120
121         /**
122          * Loads all identities that the given identities trusts with a score of
123          * more than 0 and the (optional) given context.
124          *
125          * @param ownIdentity
126          *            The own identity
127          * @param context
128          *            The context to filter, or {@code null}
129          * @return All trusted identities
130          * @throws PluginException
131          *             if an error occured talking to the Web of Trust plugin
132          */
133         public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity, String context) throws PluginException {
134                 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentitiesByScore").put("TreeOwner", ownIdentity.getId()).put("Selection", "+").put("Context", (context == null) ? "" : context).get());
135                 SimpleFieldSet fields = reply.getFields();
136                 Set<Identity> identities = new HashSet<Identity>();
137                 int identityCounter = -1;
138                 while (true) {
139                         String id = fields.get("Identity" + ++identityCounter);
140                         if (id == null) {
141                                 break;
142                         }
143                         String nickname = fields.get("Nickname" + identityCounter);
144                         String requestUri = fields.get("RequestURI" + identityCounter);
145                         DefaultIdentity identity = new DefaultIdentity(this, id, nickname, requestUri);
146                         identity.setContextsPrivate(parseContexts("Contexts" + identityCounter + ".", fields));
147                         identity.setPropertiesPrivate(parseProperties("Properties" + identityCounter + ".", fields));
148                         identities.add(identity);
149                 }
150                 return identities;
151         }
152
153         /**
154          * Adds the given context to the given identity.
155          *
156          * @param ownIdentity
157          *            The identity to add the context to
158          * @param context
159          *            The context to add
160          * @throws PluginException
161          *             if an error occured talking to the Web of Trust plugin
162          */
163         public void addContext(OwnIdentity ownIdentity, String context) throws PluginException {
164                 performRequest(SimpleFieldSetConstructor.create().put("Message", "AddContext").put("Identity", ownIdentity.getId()).put("Context", context).get());
165         }
166
167         /**
168          * Removes the given context from the given identity.
169          *
170          * @param ownIdentity
171          *            The identity to remove the context from
172          * @param context
173          *            The context to remove
174          * @throws PluginException
175          *             if an error occured talking to the Web of Trust plugin
176          */
177         public void removeContext(OwnIdentity ownIdentity, String context) throws PluginException {
178                 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveContext").put("Identity", ownIdentity.getId()).put("Context", context).get());
179         }
180
181         /**
182          * Returns the value of the property with the given name.
183          *
184          * @param identity
185          *            The identity whose properties to check
186          * @param name
187          *            The name of the property to return
188          * @return The value of the property, or {@code null} if there is no value
189          * @throws PluginException
190          *             if an error occured talking to the Web of Trust plugin
191          */
192         public String getProperty(Identity identity, String name) throws PluginException {
193                 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetProperty").put("Identity", identity.getId()).put("Property", name).get());
194                 return reply.getFields().get("Property");
195         }
196
197         /**
198          * Sets the property with the given name to the given value.
199          *
200          * @param ownIdentity
201          *            The identity to set the property on
202          * @param name
203          *            The name of the property to set
204          * @param value
205          *            The value to set
206          * @throws PluginException
207          *             if an error occured talking to the Web of Trust plugin
208          */
209         public void setProperty(OwnIdentity ownIdentity, String name, String value) throws PluginException {
210                 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetProperty").put("Identity", ownIdentity.getId()).put("Property", name).put("Value", value).get());
211         }
212
213         /**
214          * Removes the property with the given name.
215          *
216          * @param ownIdentity
217          *            The identity to remove the property from
218          * @param name
219          *            The name of the property to remove
220          * @throws PluginException
221          *             if an error occured talking to the Web of Trust plugin
222          */
223         public void removeProperty(OwnIdentity ownIdentity, String name) throws PluginException {
224                 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveProperty").put("Identity", ownIdentity.getId()).put("Property", name).get());
225         }
226
227         /**
228          * Returns the trust for the given identity assigned to it by the given own
229          * identity.
230          *
231          * @param ownIdentity
232          *            The own identity
233          * @param identity
234          *            The identity to get the trust for
235          * @return The trust for the given identity
236          * @throws PluginException
237          *             if an error occured talking to the Web of Trust plugin
238          */
239         public Trust getTrust(OwnIdentity ownIdentity, Identity identity) throws PluginException {
240                 Reply getTrustReply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentity").put("Truster", ownIdentity.getId()).put("Identity", identity.getId()).get());
241                 String trust = getTrustReply.getFields().get("Trust");
242                 String score = getTrustReply.getFields().get("Score");
243                 String rank = getTrustReply.getFields().get("Rank");
244                 Integer explicit = null;
245                 Integer implicit = null;
246                 Integer distance = null;
247                 try {
248                         explicit = Integer.valueOf(trust);
249                 } catch (NumberFormatException nfe1) {
250                         /* ignore. */
251                 }
252                 try {
253                         implicit = Integer.valueOf(score);
254                         distance = Integer.valueOf(rank);
255                 } catch (NumberFormatException nfe1) {
256                         /* ignore. */
257                 }
258                 return new Trust(explicit, implicit, distance);
259         }
260
261         /**
262          * Sets the trust for the given identity.
263          *
264          * @param ownIdentity
265          *            The trusting identity
266          * @param identity
267          *            The trusted identity
268          * @param trust
269          *            The amount of trust (-100 thru 100)
270          * @param comment
271          *            The comment or explanation of the trust value
272          * @throws PluginException
273          *             if an error occured talking to the Web of Trust plugin
274          */
275         public void setTrust(OwnIdentity ownIdentity, Identity identity, int trust, String comment) throws PluginException {
276                 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).put("Value", String.valueOf(trust)).put("Comment", comment).get());
277         }
278
279         /**
280          * Removes any trust assignment of the given own identity for the given
281          * identity.
282          *
283          * @param ownIdentity
284          *            The own identity
285          * @param identity
286          *            The identity to remove all trust for
287          * @throws WebOfTrustException
288          *             if an error occurs
289          */
290         public void removeTrust(OwnIdentity ownIdentity, Identity identity) throws WebOfTrustException {
291                 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).get());
292         }
293
294         /**
295          * Pings the Web of Trust plugin. If the plugin can not be reached, a
296          * {@link PluginException} is thrown.
297          *
298          * @throws PluginException
299          *             if the plugin is not loaded
300          */
301         public void ping() throws PluginException {
302                 performRequest(SimpleFieldSetConstructor.create().put("Message", "Ping").get());
303         }
304
305         //
306         // PRIVATE ACTIONS
307         //
308
309         /**
310          * Parses the contexts from the given fields.
311          *
312          * @param prefix
313          *            The prefix to use to access the contexts
314          * @param fields
315          *            The fields to parse the contexts from
316          * @return The parsed contexts
317          */
318         private Set<String> parseContexts(String prefix, SimpleFieldSet fields) {
319                 Set<String> contexts = new HashSet<String>();
320                 int contextCounter = -1;
321                 while (true) {
322                         String context = fields.get(prefix + "Context" + ++contextCounter);
323                         if (context == null) {
324                                 break;
325                         }
326                         contexts.add(context);
327                 }
328                 return contexts;
329         }
330
331         /**
332          * Parses the properties from the given fields.
333          *
334          * @param prefix
335          *            The prefix to use to access the properties
336          * @param fields
337          *            The fields to parse the properties from
338          * @return The parsed properties
339          */
340         private Map<String, String> parseProperties(String prefix, SimpleFieldSet fields) {
341                 Map<String, String> properties = new HashMap<String, String>();
342                 int propertiesCounter = -1;
343                 while (true) {
344                         String propertyName = fields.get(prefix + "Property" + ++propertiesCounter + ".Name");
345                         if (propertyName == null) {
346                                 break;
347                         }
348                         String propertyValue = fields.get(prefix + "Property" + propertiesCounter + ".Value");
349                         properties.put(propertyName, propertyValue);
350                 }
351                 return properties;
352         }
353
354         /**
355          * Sends a request containing the given fields and waits for the target
356          * message.
357          *
358          * @param fields
359          *            The fields of the message
360          * @return The reply message
361          * @throws PluginException
362          *             if the request could not be sent
363          */
364         private Reply performRequest(SimpleFieldSet fields) throws PluginException {
365                 return performRequest(fields, null);
366         }
367
368         /**
369          * Sends a request containing the given fields and waits for the target
370          * message.
371          *
372          * @param fields
373          *            The fields of the message
374          * @param data
375          *            The payload of the message
376          * @return The reply message
377          * @throws PluginException
378          *             if the request could not be sent
379          */
380         private synchronized Reply performRequest(SimpleFieldSet fields, Bucket data) throws PluginException {
381                 reply = new Reply();
382                 logger.log(Level.FINE, "Sending FCP Request: " + fields.get("Message"));
383                 synchronized (reply) {
384                         pluginConnector.sendRequest(WOT_PLUGIN_NAME, PLUGIN_CONNECTION_IDENTIFIER, fields, data);
385                         try {
386                                 reply.wait();
387                         } catch (InterruptedException ie1) {
388                                 logger.log(Level.WARNING, "Got interrupted while waiting for reply on " + fields.get("Message") + ".", ie1);
389                         }
390                 }
391                 logger.log(Level.FINEST, "Received FCP Response for %s: %s", new Object[] { fields.get("Message"), (reply.getFields() != null) ? reply.getFields().get("Message") : null });
392                 if ((reply.getFields() == null) || "Error".equals(reply.getFields().get("Message"))) {
393                         throw new PluginException("Could not perform request for " + fields.get("Message"));
394                 }
395                 return reply;
396         }
397
398         //
399         // INTERFACE ConnectorListener
400         //
401
402         /**
403          * {@inheritDoc}
404          */
405         @Override
406         public void receivedReply(PluginConnector pluginConnector, SimpleFieldSet fields, Bucket data) {
407                 String messageName = fields.get("Message");
408                 logger.log(Level.FINEST, "Received Reply from Plugin: " + messageName);
409                 synchronized (reply) {
410                         reply.setFields(fields);
411                         reply.setData(data);
412                         reply.notify();
413                 }
414         }
415
416         /**
417          * Container for the data of the reply from a plugin.
418          *
419          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
420          */
421         private static class Reply {
422
423                 /** The fields of the reply. */
424                 private SimpleFieldSet fields;
425
426                 /** The payload of the reply. */
427                 private Bucket data;
428
429                 /** Empty constructor. */
430                 public Reply() {
431                         /* do nothing. */
432                 }
433
434                 /**
435                  * Returns the fields of the reply.
436                  *
437                  * @return The fields of the reply
438                  */
439                 public SimpleFieldSet getFields() {
440                         return fields;
441                 }
442
443                 /**
444                  * Sets the fields of the reply.
445                  *
446                  * @param fields
447                  *            The fields of the reply
448                  */
449                 public void setFields(SimpleFieldSet fields) {
450                         this.fields = fields;
451                 }
452
453                 /**
454                  * Returns the payload of the reply.
455                  *
456                  * @return The payload of the reply (may be {@code null})
457                  */
458                 @SuppressWarnings("unused")
459                 public Bucket getData() {
460                         return data;
461                 }
462
463                 /**
464                  * Sets the payload of the reply.
465                  *
466                  * @param data
467                  *            The payload of the reply (may be {@code null})
468                  */
469                 public void setData(Bucket data) {
470                         this.data = data;
471                 }
472
473         }
474
475         /**
476          * Helper method to create {@link SimpleFieldSet}s with terser code.
477          *
478          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
479          */
480         private static class SimpleFieldSetConstructor {
481
482                 /** The field set being created. */
483                 private SimpleFieldSet simpleFieldSet;
484
485                 /**
486                  * Creates a new simple field set constructor.
487                  *
488                  * @param shortLived
489                  *            {@code true} if the resulting simple field set should be
490                  *            short-lived, {@code false} otherwise
491                  */
492                 private SimpleFieldSetConstructor(boolean shortLived) {
493                         simpleFieldSet = new SimpleFieldSet(shortLived);
494                 }
495
496                 //
497                 // ACCESSORS
498                 //
499
500                 /**
501                  * Returns the created simple field set.
502                  *
503                  * @return The created simple field set
504                  */
505                 public SimpleFieldSet get() {
506                         return simpleFieldSet;
507                 }
508
509                 /**
510                  * Sets the field with the given name to the given value.
511                  *
512                  * @param name
513                  *            The name of the fleld
514                  * @param value
515                  *            The value of the field
516                  * @return This constructor (for method chaining)
517                  */
518                 public SimpleFieldSetConstructor put(String name, String value) {
519                         simpleFieldSet.putOverwrite(name, value);
520                         return this;
521                 }
522
523                 //
524                 // ACTIONS
525                 //
526
527                 /**
528                  * Creates a new simple field set constructor.
529                  *
530                  * @return The created simple field set constructor
531                  */
532                 public static SimpleFieldSetConstructor create() {
533                         return create(true);
534                 }
535
536                 /**
537                  * Creates a new simple field set constructor.
538                  *
539                  * @param shortLived
540                  *            {@code true} if the resulting simple field set should be
541                  *            short-lived, {@code false} otherwise
542                  * @return The created simple field set constructor
543                  */
544                 public static SimpleFieldSetConstructor create(boolean shortLived) {
545                         SimpleFieldSetConstructor simpleFieldSetConstructor = new SimpleFieldSetConstructor(shortLived);
546                         return simpleFieldSetConstructor;
547                 }
548
549         }
550
551 }