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