073db64a86816d20f007d881555926ecd26d4582
[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(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          * Sets the trust for the given identity.
223          *
224          * @param ownIdentity
225          *            The trusting identity
226          * @param identity
227          *            The trusted identity
228          * @param trust
229          *            The amount of trust (-100 thru 100)
230          * @param comment
231          *            The comment or explanation of the trust value
232          * @throws PluginException
233          *             if an error occured talking to the Web of Trust plugin
234          */
235         public void setTrust(OwnIdentity ownIdentity, Identity identity, int trust, String comment) throws PluginException {
236                 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).put("Value", String.valueOf(trust)).put("Comment", comment).get(), "TrustSet");
237         }
238
239         /**
240          * Pings the Web of Trust plugin. If the plugin can not be reached, a
241          * {@link PluginException} is thrown.
242          *
243          * @throws PluginException
244          *             if the plugin is not loaded
245          */
246         public void ping() throws PluginException {
247                 performRequest(SimpleFieldSetConstructor.create().put("Message", "Ping").get(), "Pong");
248         }
249
250         //
251         // PRIVATE ACTIONS
252         //
253
254         /**
255          * Parses the contexts from the given fields.
256          *
257          * @param prefix
258          *            The prefix to use to access the contexts
259          * @param fields
260          *            The fields to parse the contexts from
261          * @return The parsed contexts
262          */
263         private Set<String> parseContexts(String prefix, SimpleFieldSet fields) {
264                 Set<String> contexts = new HashSet<String>();
265                 int contextCounter = -1;
266                 while (true) {
267                         String context = fields.get(prefix + "Context" + ++contextCounter);
268                         if (context == null) {
269                                 break;
270                         }
271                         contexts.add(context);
272                 }
273                 return contexts;
274         }
275
276         /**
277          * Parses the properties from the given fields.
278          *
279          * @param prefix
280          *            The prefix to use to access the properties
281          * @param fields
282          *            The fields to parse the properties from
283          * @return The parsed properties
284          */
285         private Map<String, String> parseProperties(String prefix, SimpleFieldSet fields) {
286                 Map<String, String> properties = new HashMap<String, String>();
287                 int propertiesCounter = -1;
288                 while (true) {
289                         String propertyName = fields.get(prefix + "Property" + ++propertiesCounter + ".Name");
290                         if (propertyName == null) {
291                                 break;
292                         }
293                         String propertyValue = fields.get(prefix + "Property" + propertiesCounter + ".Value");
294                         properties.put(propertyName, propertyValue);
295                 }
296                 return properties;
297         }
298
299         /**
300          * Sends a request containing the given fields and waits for the target
301          * message.
302          *
303          * @param fields
304          *            The fields of the message
305          * @param targetMessages
306          *            The messages of the reply to wait for
307          * @return The reply message
308          * @throws PluginException
309          *             if the request could not be sent
310          */
311         private Reply performRequest(SimpleFieldSet fields, String... targetMessages) throws PluginException {
312                 return performRequest(fields, null, targetMessages);
313         }
314
315         /**
316          * Sends a request containing the given fields and waits for the target
317          * message.
318          *
319          * @param fields
320          *            The fields of the message
321          * @param data
322          *            The payload of the message
323          * @param targetMessages
324          *            The messages of the reply to wait for
325          * @return The reply message
326          * @throws PluginException
327          *             if the request could not be sent
328          */
329         private Reply performRequest(SimpleFieldSet fields, Bucket data, String... targetMessages) throws PluginException {
330                 @SuppressWarnings("synthetic-access")
331                 Reply reply = new Reply();
332                 for (String targetMessage : targetMessages) {
333                         replies.put(targetMessage, reply);
334                 }
335                 replies.put("Error", reply);
336                 synchronized (reply) {
337                         pluginConnector.sendRequest(WOT_PLUGIN_NAME, PLUGIN_CONNECTION_IDENTIFIER, fields, data);
338                         try {
339                                 long now = System.currentTimeMillis();
340                                 while ((reply.getFields() == null) && ((System.currentTimeMillis() - now) < 60000)) {
341                                         reply.wait(60000 - (System.currentTimeMillis() - now));
342                                 }
343                                 if (reply.getFields() == null) {
344                                         for (String targetMessage : targetMessages) {
345                                                 replies.remove(targetMessage);
346                                         }
347                                         replies.remove("Error");
348                                         throw new PluginException("Timeout waiting for " + targetMessages[0] + "!");
349                                 }
350                         } catch (InterruptedException ie1) {
351                                 logger.log(Level.WARNING, "Got interrupted while waiting for reply on " + targetMessages[0] + ".", ie1);
352                         }
353                 }
354                 for (String targetMessage : targetMessages) {
355                         replies.remove(targetMessage);
356                 }
357                 replies.remove("Error");
358                 if ((reply.getFields() != null) && reply.getFields().get("Message").equals("Error")) {
359                         throw new PluginException("Could not perform request for " + targetMessages[0]);
360                 }
361                 return reply;
362         }
363
364         //
365         // INTERFACE ConnectorListener
366         //
367
368         /**
369          * {@inheritDoc}
370          */
371         @Override
372         public void receivedReply(PluginConnector pluginConnector, SimpleFieldSet fields, Bucket data) {
373                 String messageName = fields.get("Message");
374                 logger.log(Level.FINEST, "Received Reply from Plugin: " + messageName);
375                 Reply reply = replies.remove(messageName);
376                 if (reply == null) {
377                         logger.log(Level.FINE, "Not waiting for a “%s” message.", messageName);
378                         return;
379                 }
380                 synchronized (reply) {
381                         reply.setFields(fields);
382                         reply.setData(data);
383                         reply.notify();
384                 }
385         }
386
387         /**
388          * Container for the data of the reply from a plugin.
389          *
390          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
391          */
392         private static class Reply {
393
394                 /** The fields of the reply. */
395                 private SimpleFieldSet fields;
396
397                 /** The payload of the reply. */
398                 private Bucket data;
399
400                 /**
401                  * Returns the fields of the reply.
402                  *
403                  * @return The fields of the reply
404                  */
405                 public SimpleFieldSet getFields() {
406                         return fields;
407                 }
408
409                 /**
410                  * Sets the fields of the reply.
411                  *
412                  * @param fields
413                  *            The fields of the reply
414                  */
415                 public void setFields(SimpleFieldSet fields) {
416                         this.fields = fields;
417                 }
418
419                 /**
420                  * Returns the payload of the reply.
421                  *
422                  * @return The payload of the reply (may be {@code null})
423                  */
424                 @SuppressWarnings("unused")
425                 public Bucket getData() {
426                         return data;
427                 }
428
429                 /**
430                  * Sets the payload of the reply.
431                  *
432                  * @param data
433                  *            The payload of the reply (may be {@code null})
434                  */
435                 public void setData(Bucket data) {
436                         this.data = data;
437                 }
438
439         }
440
441         /**
442          * Helper method to create {@link SimpleFieldSet}s with terser code.
443          *
444          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
445          */
446         private static class SimpleFieldSetConstructor {
447
448                 /** The field set being created. */
449                 private SimpleFieldSet simpleFieldSet;
450
451                 /**
452                  * Creates a new simple field set constructor.
453                  *
454                  * @param shortLived
455                  *            {@code true} if the resulting simple field set should be
456                  *            short-lived, {@code false} otherwise
457                  */
458                 private SimpleFieldSetConstructor(boolean shortLived) {
459                         simpleFieldSet = new SimpleFieldSet(shortLived);
460                 }
461
462                 //
463                 // ACCESSORS
464                 //
465
466                 /**
467                  * Returns the created simple field set.
468                  *
469                  * @return The created simple field set
470                  */
471                 public SimpleFieldSet get() {
472                         return simpleFieldSet;
473                 }
474
475                 /**
476                  * Sets the field with the given name to the given value.
477                  *
478                  * @param name
479                  *            The name of the fleld
480                  * @param value
481                  *            The value of the field
482                  * @return This constructor (for method chaining)
483                  */
484                 public SimpleFieldSetConstructor put(String name, String value) {
485                         simpleFieldSet.putOverwrite(name, value);
486                         return this;
487                 }
488
489                 //
490                 // ACTIONS
491                 //
492
493                 /**
494                  * Creates a new simple field set constructor.
495                  *
496                  * @return The created simple field set constructor
497                  */
498                 public static SimpleFieldSetConstructor create() {
499                         return create(true);
500                 }
501
502                 /**
503                  * Creates a new simple field set constructor.
504                  *
505                  * @param shortLived
506                  *            {@code true} if the resulting simple field set should be
507                  *            short-lived, {@code false} otherwise
508                  * @return The created simple field set constructor
509                  */
510                 public static SimpleFieldSetConstructor create(boolean shortLived) {
511                         SimpleFieldSetConstructor simpleFieldSetConstructor = new SimpleFieldSetConstructor(shortLived);
512                         return simpleFieldSetConstructor;
513                 }
514
515         }
516
517 }