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