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