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