Add method to retrieve the trust of an identity for an own identity.
[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.Collections;
21 import java.util.HashMap;
22 import java.util.HashSet;
23 import java.util.Map;
24 import java.util.Set;
25 import java.util.logging.Level;
26 import java.util.logging.Logger;
27
28 import net.pterodactylus.sone.freenet.plugin.ConnectorListener;
29 import net.pterodactylus.sone.freenet.plugin.PluginConnector;
30 import net.pterodactylus.sone.freenet.plugin.PluginException;
31 import net.pterodactylus.util.logging.Logging;
32 import freenet.support.SimpleFieldSet;
33 import freenet.support.api.Bucket;
34
35 /**
36  * Connector for the Web of Trust plugin.
37  *
38  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
39  */
40 public class WebOfTrustConnector implements ConnectorListener {
41
42         /** The logger. */
43         private static final Logger logger = Logging.getLogger(WebOfTrustConnector.class);
44
45         /** The name of the WoT plugin. */
46         private static final String WOT_PLUGIN_NAME = "plugins.WoT.WoT";
47
48         /** A random connection identifier. */
49         private static final String PLUGIN_CONNECTION_IDENTIFIER = "Sone-WoT-Connector-" + Math.abs(Math.random());
50
51         /** The current replies that we wait for. */
52         private final Map<String, Reply> replies = Collections.synchronizedMap(new HashMap<String, Reply>());
53
54         /** The plugin connector. */
55         private final PluginConnector pluginConnector;
56
57         /**
58          * Creates a new Web of Trust connector that uses the given plugin
59          * connector.
60          *
61          * @param pluginConnector
62          *            The plugin connector
63          */
64         public WebOfTrustConnector(PluginConnector pluginConnector) {
65                 this.pluginConnector = pluginConnector;
66                 pluginConnector.addConnectorListener(WOT_PLUGIN_NAME, PLUGIN_CONNECTION_IDENTIFIER, this);
67         }
68
69         //
70         // ACTIONS
71         //
72
73         /**
74          * Loads all own identities from the Web of Trust plugin.
75          *
76          * @return All own identity
77          * @throws WebOfTrustException
78          *             if the own identities can not be loaded
79          */
80         public Set<OwnIdentity> loadAllOwnIdentities() throws WebOfTrustException {
81                 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetOwnIdentities").get(), "OwnIdentities");
82                 SimpleFieldSet fields = reply.getFields();
83                 int ownIdentityCounter = -1;
84                 Set<OwnIdentity> ownIdentities = new HashSet<OwnIdentity>();
85                 while (true) {
86                         String id = fields.get("Identity" + ++ownIdentityCounter);
87                         if (id == null) {
88                                 break;
89                         }
90                         String requestUri = fields.get("RequestURI" + ownIdentityCounter);
91                         String insertUri = fields.get("InsertURI" + ownIdentityCounter);
92                         String nickname = fields.get("Nickname" + ownIdentityCounter);
93                         DefaultOwnIdentity ownIdentity = new DefaultOwnIdentity(this, id, nickname, requestUri, insertUri);
94                         ownIdentity.setContextsPrivate(parseContexts("Contexts" + ownIdentityCounter + ".", fields));
95                         ownIdentity.setPropertiesPrivate(parseProperties("Properties" + ownIdentityCounter + ".", fields));
96                         ownIdentities.add(ownIdentity);
97                 }
98                 return ownIdentities;
99         }
100
101         /**
102          * Loads all identities that the given identities trusts with a score of
103          * more than 0.
104          *
105          * @param ownIdentity
106          *            The own identity
107          * @return All trusted identities
108          * @throws PluginException
109          *             if an error occured talking to the Web of Trust plugin
110          */
111         public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity) throws PluginException {
112                 return loadTrustedIdentities(ownIdentity, null);
113         }
114
115         /**
116          * Loads all identities that the given identities trusts with a score of
117          * more than 0 and the (optional) given context.
118          *
119          * @param ownIdentity
120          *            The own identity
121          * @param context
122          *            The context to filter, or {@code null}
123          * @return All trusted identities
124          * @throws PluginException
125          *             if an error occured talking to the Web of Trust plugin
126          */
127         public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity, String context) throws PluginException {
128                 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentitiesByScore").put("TreeOwner", ownIdentity.getId()).put("Selection", "+").put("Context", (context == null) ? "" : context).get(), "Identities");
129                 SimpleFieldSet fields = reply.getFields();
130                 Set<Identity> identities = new HashSet<Identity>();
131                 int identityCounter = -1;
132                 while (true) {
133                         String id = fields.get("Identity" + ++identityCounter);
134                         if (id == null) {
135                                 break;
136                         }
137                         String nickname = fields.get("Nickname" + identityCounter);
138                         String requestUri = fields.get("RequestURI" + identityCounter);
139                         DefaultIdentity identity = new DefaultIdentity(this, id, nickname, requestUri);
140                         identity.setContextsPrivate(parseContexts("Contexts" + identityCounter + ".", fields));
141                         identity.setPropertiesPrivate(parseProperties("Properties" + identityCounter + ".", fields));
142                         identities.add(identity);
143                 }
144                 return identities;
145         }
146
147         /**
148          * Adds the given context to the given identity.
149          *
150          * @param ownIdentity
151          *            The identity to add the context to
152          * @param context
153          *            The context to add
154          * @throws PluginException
155          *             if an error occured talking to the Web of Trust plugin
156          */
157         public void addContext(OwnIdentity ownIdentity, String context) throws PluginException {
158                 performRequest(SimpleFieldSetConstructor.create().put("Message", "AddContext").put("Identity", ownIdentity.getId()).put("Context", context).get(), "ContextAdded");
159         }
160
161         /**
162          * Removes the given context from the given identity.
163          *
164          * @param ownIdentity
165          *            The identity to remove the context from
166          * @param context
167          *            The context to remove
168          * @throws PluginException
169          *             if an error occured talking to the Web of Trust plugin
170          */
171         public void removeContext(OwnIdentity ownIdentity, String context) throws PluginException {
172                 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveContext").put("Identity", ownIdentity.getId()).put("Context", context).get(), "ContextRemoved");
173         }
174
175         /**
176          * Returns the value of the property with the given name.
177          *
178          * @param identity
179          *            The identity whose properties to check
180          * @param name
181          *            The name of the property to return
182          * @return The value of the property, or {@code null} if there is no value
183          * @throws PluginException
184          *             if an error occured talking to the Web of Trust plugin
185          */
186         public String getProperty(Identity identity, String name) throws PluginException {
187                 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetProperty").put("Identity", identity.getId()).put("Property", name).get(), "PropertyValue");
188                 return reply.getFields().get("Property");
189         }
190
191         /**
192          * Sets the property with the given name to the given value.
193          *
194          * @param ownIdentity
195          *            The identity to set the property on
196          * @param name
197          *            The name of the property to set
198          * @param value
199          *            The value to set
200          * @throws PluginException
201          *             if an error occured talking to the Web of Trust plugin
202          */
203         public void setProperty(OwnIdentity ownIdentity, String name, String value) throws PluginException {
204                 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetProperty").put("Identity", ownIdentity.getId()).put("Property", name).put("Value", value).get(), "PropertyAdded");
205         }
206
207         /**
208          * Removes the property with the given name.
209          *
210          * @param ownIdentity
211          *            The identity to remove the property from
212          * @param name
213          *            The name of the property to remove
214          * @throws PluginException
215          *             if an error occured talking to the Web of Trust plugin
216          */
217         public void removeProperty(OwnIdentity ownIdentity, String name) throws PluginException {
218                 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveProperty").put("Identity", ownIdentity.getId()).put("Property", name).get(), "PropertyRemoved");
219         }
220
221         /**
222          * Returns the trust for the given identity assigned to it by the given own
223          * identity.
224          *
225          * @param ownIdentity
226          *            The own identity
227          * @param identity
228          *            The identity to get the trust for
229          * @return The trust for the given identity
230          * @throws PluginException
231          *             if an error occured talking to the Web of Trust plugin
232          */
233         public Trust getTrust(OwnIdentity ownIdentity, Identity identity) throws PluginException {
234                 Reply getTrustReply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentity").put("TreeOwner", ownIdentity.getId()).put("Identity", identity.getId()).get(), "Identity");
235                 String trust = getTrustReply.getFields().get("Trust");
236                 String score = getTrustReply.getFields().get("Score");
237                 String rank = getTrustReply.getFields().get("Rank");
238                 Integer explicit = null;
239                 Integer implicit = null;
240                 Integer distance = null;
241                 try {
242                         explicit = Integer.valueOf(trust);
243                 } catch (NumberFormatException nfe1) {
244                         /* ignore. */
245                 }
246                 try {
247                         implicit = Integer.valueOf(score);
248                         distance = Integer.valueOf(rank);
249                 } catch (NumberFormatException nfe1) {
250                         /* ignore. */
251                 }
252                 return new Trust(explicit, implicit, distance);
253         }
254
255         /**
256          * Sets the trust for the given identity.
257          *
258          * @param ownIdentity
259          *            The trusting identity
260          * @param identity
261          *            The trusted identity
262          * @param trust
263          *            The amount of trust (-100 thru 100)
264          * @param comment
265          *            The comment or explanation of the trust value
266          * @throws PluginException
267          *             if an error occured talking to the Web of Trust plugin
268          */
269         public void setTrust(OwnIdentity ownIdentity, Identity identity, int trust, String comment) throws PluginException {
270                 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).put("Value", String.valueOf(trust)).put("Comment", comment).get(), "TrustSet");
271         }
272
273         /**
274          * Pings the Web of Trust plugin. If the plugin can not be reached, a
275          * {@link PluginException} is thrown.
276          *
277          * @throws PluginException
278          *             if the plugin is not loaded
279          */
280         public void ping() throws PluginException {
281                 performRequest(SimpleFieldSetConstructor.create().put("Message", "Ping").get(), "Pong");
282         }
283
284         //
285         // PRIVATE ACTIONS
286         //
287
288         /**
289          * Parses the contexts from the given fields.
290          *
291          * @param prefix
292          *            The prefix to use to access the contexts
293          * @param fields
294          *            The fields to parse the contexts from
295          * @return The parsed contexts
296          */
297         private Set<String> parseContexts(String prefix, SimpleFieldSet fields) {
298                 Set<String> contexts = new HashSet<String>();
299                 int contextCounter = -1;
300                 while (true) {
301                         String context = fields.get(prefix + "Context" + ++contextCounter);
302                         if (context == null) {
303                                 break;
304                         }
305                         contexts.add(context);
306                 }
307                 return contexts;
308         }
309
310         /**
311          * Parses the properties from the given fields.
312          *
313          * @param prefix
314          *            The prefix to use to access the properties
315          * @param fields
316          *            The fields to parse the properties from
317          * @return The parsed properties
318          */
319         private Map<String, String> parseProperties(String prefix, SimpleFieldSet fields) {
320                 Map<String, String> properties = new HashMap<String, String>();
321                 int propertiesCounter = -1;
322                 while (true) {
323                         String propertyName = fields.get(prefix + "Property" + ++propertiesCounter + ".Name");
324                         if (propertyName == null) {
325                                 break;
326                         }
327                         String propertyValue = fields.get(prefix + "Property" + propertiesCounter + ".Value");
328                         properties.put(propertyName, propertyValue);
329                 }
330                 return properties;
331         }
332
333         /**
334          * Sends a request containing the given fields and waits for the target
335          * message.
336          *
337          * @param fields
338          *            The fields of the message
339          * @param targetMessages
340          *            The messages of the reply to wait for
341          * @return The reply message
342          * @throws PluginException
343          *             if the request could not be sent
344          */
345         private Reply performRequest(SimpleFieldSet fields, String... targetMessages) throws PluginException {
346                 return performRequest(fields, null, targetMessages);
347         }
348
349         /**
350          * Sends a request containing the given fields and waits for the target
351          * message.
352          *
353          * @param fields
354          *            The fields of the message
355          * @param data
356          *            The payload of the message
357          * @param targetMessages
358          *            The messages of the reply to wait for
359          * @return The reply message
360          * @throws PluginException
361          *             if the request could not be sent
362          */
363         private Reply performRequest(SimpleFieldSet fields, Bucket data, String... targetMessages) throws PluginException {
364                 @SuppressWarnings("synthetic-access")
365                 Reply reply = new Reply();
366                 for (String targetMessage : targetMessages) {
367                         replies.put(targetMessage, reply);
368                 }
369                 replies.put("Error", reply);
370                 synchronized (reply) {
371                         pluginConnector.sendRequest(WOT_PLUGIN_NAME, PLUGIN_CONNECTION_IDENTIFIER, fields, data);
372                         try {
373                                 long now = System.currentTimeMillis();
374                                 while ((reply.getFields() == null) && ((System.currentTimeMillis() - now) < 60000)) {
375                                         reply.wait(60000 - (System.currentTimeMillis() - now));
376                                 }
377                                 if (reply.getFields() == null) {
378                                         for (String targetMessage : targetMessages) {
379                                                 replies.remove(targetMessage);
380                                         }
381                                         replies.remove("Error");
382                                         throw new PluginException("Timeout waiting for " + targetMessages[0] + "!");
383                                 }
384                         } catch (InterruptedException ie1) {
385                                 logger.log(Level.WARNING, "Got interrupted while waiting for reply on " + targetMessages[0] + ".", ie1);
386                         }
387                 }
388                 for (String targetMessage : targetMessages) {
389                         replies.remove(targetMessage);
390                 }
391                 replies.remove("Error");
392                 if ((reply.getFields() != null) && reply.getFields().get("Message").equals("Error")) {
393                         throw new PluginException("Could not perform request for " + targetMessages[0]);
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                 Reply reply = replies.remove(messageName);
410                 if (reply == null) {
411                         logger.log(Level.FINE, "Not waiting for a “%s” message.", messageName);
412                         return;
413                 }
414                 synchronized (reply) {
415                         reply.setFields(fields);
416                         reply.setData(data);
417                         reply.notify();
418                 }
419         }
420
421         /**
422          * Container for the data of the reply from a plugin.
423          *
424          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
425          */
426         private static class Reply {
427
428                 /** The fields of the reply. */
429                 private SimpleFieldSet fields;
430
431                 /** The payload of the reply. */
432                 private Bucket data;
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 }