2 * Sone - WebOfTrustConnector.java - Copyright © 2010 David Roden
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.
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.
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/>.
18 package net.pterodactylus.wotns.freenet.wot;
20 import java.util.HashMap;
21 import java.util.HashSet;
24 import java.util.logging.Level;
25 import java.util.logging.Logger;
27 import net.pterodactylus.util.logging.Logging;
28 import net.pterodactylus.util.number.Numbers;
29 import net.pterodactylus.wotns.freenet.plugin.ConnectorListener;
30 import net.pterodactylus.wotns.freenet.plugin.PluginConnector;
31 import net.pterodactylus.wotns.freenet.plugin.PluginException;
32 import freenet.support.SimpleFieldSet;
33 import freenet.support.api.Bucket;
36 * Connector for the Web of Trust plugin.
38 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
40 public class WebOfTrustConnector implements ConnectorListener {
43 private static final Logger logger = Logging.getLogger(WebOfTrustConnector.class);
45 /** The name of the WoT plugin. */
46 private static final String WOT_PLUGIN_NAME = "plugins.WebOfTrust.WebOfTrust";
48 /** A random connection identifier. */
49 private static final String PLUGIN_CONNECTION_IDENTIFIER = "WoTNS-WoT-Connector-" + Math.abs(Math.random());
51 /** The current reply. */
54 /** The plugin connector. */
55 private final PluginConnector pluginConnector;
58 * Creates a new Web of Trust connector that uses the given plugin
61 * @param pluginConnector
62 * The plugin connector
64 public WebOfTrustConnector(PluginConnector pluginConnector) {
65 this.pluginConnector = pluginConnector;
66 pluginConnector.addConnectorListener(WOT_PLUGIN_NAME, PLUGIN_CONNECTION_IDENTIFIER, this);
74 * Stops the web of trust connector and disconnects from the plugin
78 pluginConnector.removeConnectorListener(WOT_PLUGIN_NAME, PLUGIN_CONNECTION_IDENTIFIER, this);
82 * Loads all own identities from the Web of Trust plugin.
84 * @return All own identity
85 * @throws WebOfTrustException
86 * if the own identities can not be loaded
88 public Set<OwnIdentity> loadAllOwnIdentities() throws WebOfTrustException {
89 @SuppressWarnings("hiding")
90 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetOwnIdentities").get());
91 SimpleFieldSet fields = reply.getFields();
92 int ownIdentityCounter = -1;
93 Set<OwnIdentity> ownIdentities = new HashSet<OwnIdentity>();
95 String id = fields.get("Identity" + ++ownIdentityCounter);
99 String requestUri = fields.get("RequestURI" + ownIdentityCounter);
100 String insertUri = fields.get("InsertURI" + ownIdentityCounter);
101 String nickname = fields.get("Nickname" + ownIdentityCounter);
102 DefaultOwnIdentity ownIdentity = new DefaultOwnIdentity(this, id, nickname, requestUri, insertUri);
103 ownIdentity.setContextsPrivate(parseContexts("Contexts" + ownIdentityCounter + ".", fields));
104 ownIdentity.setPropertiesPrivate(parseProperties("Properties" + ownIdentityCounter + ".", fields));
105 ownIdentities.add(ownIdentity);
107 return ownIdentities;
111 * Loads all identities that the given identities trusts with a score of
116 * @return All trusted identities
117 * @throws WebOfTrustException
118 * if an error occured talking to the Web of Trust plugin
120 public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity) throws WebOfTrustException {
121 return loadTrustedIdentities(ownIdentity, null);
125 * Loads all identities that the given identities trusts with a score of
126 * more than 0 and the (optional) given context.
131 * The context to filter, or {@code null}
132 * @return All trusted identities
133 * @throws WebOfTrustException
134 * if an error occured talking to the Web of Trust plugin
136 public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity, String context) throws WebOfTrustException {
137 @SuppressWarnings("hiding")
138 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentitiesByScore").put("TreeOwner", ownIdentity.getId()).put("Selection", "+").put("Context", (context == null) ? "" : context).get());
139 SimpleFieldSet fields = reply.getFields();
140 Set<Identity> identities = new HashSet<Identity>();
141 int identityCounter = -1;
143 String id = fields.get("Identity" + ++identityCounter);
147 String nickname = fields.get("Nickname" + identityCounter);
148 String requestUri = fields.get("RequestURI" + identityCounter);
149 DefaultIdentity identity = new DefaultIdentity(this, id, nickname, requestUri);
150 identity.setContextsPrivate(parseContexts("Contexts" + identityCounter + ".", fields));
151 identity.setPropertiesPrivate(parseProperties("Properties" + identityCounter + ".", fields));
152 identity.setTrustPrivate(ownIdentity, new Trust(Numbers.safeParseInteger(fields.get("Trust" + identityCounter)), Numbers.safeParseInteger(fields.get("Score" + identityCounter)), Numbers.safeParseInteger(fields.get("Rank" + identityCounter))));
153 identities.add(identity);
159 * Adds the given context to the given identity.
162 * The identity to add the context to
165 * @throws PluginException
166 * if an error occured talking to the Web of Trust plugin
168 public void addContext(OwnIdentity ownIdentity, String context) throws PluginException {
169 performRequest(SimpleFieldSetConstructor.create().put("Message", "AddContext").put("Identity", ownIdentity.getId()).put("Context", context).get());
173 * Removes the given context from the given identity.
176 * The identity to remove the context from
178 * The context to remove
179 * @throws PluginException
180 * if an error occured talking to the Web of Trust plugin
182 public void removeContext(OwnIdentity ownIdentity, String context) throws PluginException {
183 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveContext").put("Identity", ownIdentity.getId()).put("Context", context).get());
187 * Returns the value of the property with the given name.
190 * The identity whose properties to check
192 * The name of the property to return
193 * @return The value of the property, or {@code null} if there is no value
194 * @throws PluginException
195 * if an error occured talking to the Web of Trust plugin
197 public String getProperty(Identity identity, String name) throws PluginException {
198 @SuppressWarnings("hiding")
199 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetProperty").put("Identity", identity.getId()).put("Property", name).get());
200 return reply.getFields().get("Property");
204 * Sets the property with the given name to the given value.
207 * The identity to set the property on
209 * The name of the property to set
212 * @throws PluginException
213 * if an error occured talking to the Web of Trust plugin
215 public void setProperty(OwnIdentity ownIdentity, String name, String value) throws PluginException {
216 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetProperty").put("Identity", ownIdentity.getId()).put("Property", name).put("Value", value).get());
220 * Removes the property with the given name.
223 * The identity to remove the property from
225 * The name of the property to remove
226 * @throws PluginException
227 * if an error occured talking to the Web of Trust plugin
229 public void removeProperty(OwnIdentity ownIdentity, String name) throws PluginException {
230 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveProperty").put("Identity", ownIdentity.getId()).put("Property", name).get());
234 * Returns the trust for the given identity assigned to it by the given own
240 * The identity to get the trust for
241 * @return The trust for the given identity
242 * @throws PluginException
243 * if an error occured talking to the Web of Trust plugin
245 public Trust getTrust(OwnIdentity ownIdentity, Identity identity) throws PluginException {
246 Reply getTrustReply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentity").put("Truster", ownIdentity.getId()).put("Identity", identity.getId()).get());
247 String trust = getTrustReply.getFields().get("Trust");
248 String score = getTrustReply.getFields().get("Score");
249 String rank = getTrustReply.getFields().get("Rank");
250 Integer explicit = null;
251 Integer implicit = null;
252 Integer distance = null;
254 explicit = Integer.valueOf(trust);
255 } catch (NumberFormatException nfe1) {
259 implicit = Integer.valueOf(score);
260 distance = Integer.valueOf(rank);
261 } catch (NumberFormatException nfe1) {
264 return new Trust(explicit, implicit, distance);
268 * Sets the trust for the given identity.
271 * The trusting identity
273 * The trusted identity
275 * The amount of trust (-100 thru 100)
277 * The comment or explanation of the trust value
278 * @throws PluginException
279 * if an error occured talking to the Web of Trust plugin
281 public void setTrust(OwnIdentity ownIdentity, Identity identity, int trust, String comment) throws PluginException {
282 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).put("Value", String.valueOf(trust)).put("Comment", comment).get());
286 * Removes any trust assignment of the given own identity for the given
292 * The identity to remove all trust for
293 * @throws WebOfTrustException
296 public void removeTrust(OwnIdentity ownIdentity, Identity identity) throws WebOfTrustException {
297 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).get());
301 * Pings the Web of Trust plugin. If the plugin can not be reached, a
302 * {@link PluginException} is thrown.
304 * @throws PluginException
305 * if the plugin is not loaded
307 public void ping() throws PluginException {
308 performRequest(SimpleFieldSetConstructor.create().put("Message", "Ping").get());
316 * Parses the contexts from the given fields.
319 * The prefix to use to access the contexts
321 * The fields to parse the contexts from
322 * @return The parsed contexts
324 private Set<String> parseContexts(String prefix, SimpleFieldSet fields) {
325 Set<String> contexts = new HashSet<String>();
326 int contextCounter = -1;
328 String context = fields.get(prefix + "Context" + ++contextCounter);
329 if (context == null) {
332 contexts.add(context);
338 * Parses the properties from the given fields.
341 * The prefix to use to access the properties
343 * The fields to parse the properties from
344 * @return The parsed properties
346 private Map<String, String> parseProperties(String prefix, SimpleFieldSet fields) {
347 Map<String, String> properties = new HashMap<String, String>();
348 int propertiesCounter = -1;
350 String propertyName = fields.get(prefix + "Property" + ++propertiesCounter + ".Name");
351 if (propertyName == null) {
354 String propertyValue = fields.get(prefix + "Property" + propertiesCounter + ".Value");
355 properties.put(propertyName, propertyValue);
361 * Sends a request containing the given fields and waits for the target
365 * The fields of the message
366 * @return The reply message
367 * @throws PluginException
368 * if the request could not be sent
370 private Reply performRequest(SimpleFieldSet fields) throws PluginException {
371 return performRequest(fields, null);
375 * Sends a request containing the given fields and waits for the target
379 * The fields of the message
381 * The payload of the message
382 * @return The reply message
383 * @throws PluginException
384 * if the request could not be sent
386 private synchronized Reply performRequest(SimpleFieldSet fields, Bucket data) throws PluginException {
388 logger.log(Level.FINE, "Sending FCP Request: " + fields.get("Message"));
389 synchronized (reply) {
390 pluginConnector.sendRequest(WOT_PLUGIN_NAME, PLUGIN_CONNECTION_IDENTIFIER, fields, data);
393 } catch (InterruptedException ie1) {
394 logger.log(Level.WARNING, "Got interrupted while waiting for reply on " + fields.get("Message") + ".", ie1);
397 logger.log(Level.FINEST, "Received FCP Response for %s: %s", new Object[] { fields.get("Message"), (reply.getFields() != null) ? reply.getFields().get("Message") : null });
398 if ((reply.getFields() == null) || "Error".equals(reply.getFields().get("Message"))) {
399 throw new PluginException("Could not perform request for " + fields.get("Message"));
405 // INTERFACE ConnectorListener
412 public void receivedReply(@SuppressWarnings("hiding") PluginConnector pluginConnector, SimpleFieldSet fields, Bucket data) {
413 String messageName = fields.get("Message");
414 logger.log(Level.FINEST, "Received Reply from Plugin: " + messageName);
415 synchronized (reply) {
416 reply.setFields(fields);
423 * Container for the data of the reply from a plugin.
425 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
427 private static class Reply {
429 /** The fields of the reply. */
430 private SimpleFieldSet fields;
432 /** The payload of the reply. */
435 /** Empty constructor. */
441 * Returns the fields of the reply.
443 * @return The fields of the reply
445 public SimpleFieldSet getFields() {
450 * Sets the fields of the reply.
453 * The fields of the reply
455 public void setFields(SimpleFieldSet fields) {
456 this.fields = fields;
460 * Returns the payload of the reply.
462 * @return The payload of the reply (may be {@code null})
464 @SuppressWarnings("unused")
465 public Bucket getData() {
470 * Sets the payload of the reply.
473 * The payload of the reply (may be {@code null})
475 public void setData(Bucket data) {
482 * Helper method to create {@link SimpleFieldSet}s with terser code.
484 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
486 private static class SimpleFieldSetConstructor {
488 /** The field set being created. */
489 private SimpleFieldSet simpleFieldSet;
492 * Creates a new simple field set constructor.
495 * {@code true} if the resulting simple field set should be
496 * short-lived, {@code false} otherwise
498 private SimpleFieldSetConstructor(boolean shortLived) {
499 simpleFieldSet = new SimpleFieldSet(shortLived);
507 * Returns the created simple field set.
509 * @return The created simple field set
511 public SimpleFieldSet get() {
512 return simpleFieldSet;
516 * Sets the field with the given name to the given value.
519 * The name of the fleld
521 * The value of the field
522 * @return This constructor (for method chaining)
524 public SimpleFieldSetConstructor put(String name, String value) {
525 simpleFieldSet.putOverwrite(name, value);
534 * Creates a new simple field set constructor.
536 * @return The created simple field set constructor
538 public static SimpleFieldSetConstructor create() {
543 * Creates a new simple field set constructor.
546 * {@code true} if the resulting simple field set should be
547 * short-lived, {@code false} otherwise
548 * @return The created simple field set constructor
550 public static SimpleFieldSetConstructor create(boolean shortLived) {
551 SimpleFieldSetConstructor simpleFieldSetConstructor = new SimpleFieldSetConstructor(shortLived);
552 return simpleFieldSetConstructor;