2 * Sone - WebOfTrustConnector.java - Copyright © 2010–2012 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.sone.freenet.wot;
20 import java.util.HashMap;
21 import java.util.HashSet;
24 import java.util.concurrent.atomic.AtomicLong;
25 import java.util.logging.Level;
26 import java.util.logging.Logger;
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 net.pterodactylus.util.number.Numbers;
33 import freenet.support.SimpleFieldSet;
34 import freenet.support.api.Bucket;
37 * Connector for the Web of Trust plugin.
39 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
41 public class WebOfTrustConnector {
44 private static final Logger logger = Logging.getLogger(WebOfTrustConnector.class);
46 /** The name of the WoT plugin. */
47 private static final String WOT_PLUGIN_NAME = "plugins.WebOfTrust.WebOfTrust";
49 /** Counter for connection identifiers. */
50 private final AtomicLong counter = new AtomicLong();
52 /** The plugin connector. */
53 private final PluginConnector pluginConnector;
56 * Creates a new Web of Trust connector that uses the given plugin
59 * @param pluginConnector
60 * The plugin connector
62 public WebOfTrustConnector(PluginConnector pluginConnector) {
63 this.pluginConnector = pluginConnector;
71 * Stops the web of trust connector.
78 * Loads all own identities from the Web of Trust plugin.
80 * @return All own identity
81 * @throws WebOfTrustException
82 * if the own identities can not be loaded
84 public Set<OwnIdentity> loadAllOwnIdentities() throws WebOfTrustException {
85 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetOwnIdentities").get());
86 SimpleFieldSet fields = reply.getFields();
87 int ownIdentityCounter = -1;
88 Set<OwnIdentity> ownIdentities = new HashSet<OwnIdentity>();
90 String id = fields.get("Identity" + ++ownIdentityCounter);
94 String requestUri = fields.get("RequestURI" + ownIdentityCounter);
95 String insertUri = fields.get("InsertURI" + ownIdentityCounter);
96 String nickname = fields.get("Nickname" + ownIdentityCounter);
97 DefaultOwnIdentity ownIdentity = new DefaultOwnIdentity(id, nickname, requestUri, insertUri);
98 ownIdentity.setContexts(parseContexts("Contexts" + ownIdentityCounter + ".", fields));
99 ownIdentity.setProperties(parseProperties("Properties" + ownIdentityCounter + ".", fields));
100 ownIdentities.add(ownIdentity);
102 return ownIdentities;
106 * Loads all identities that the given identities trusts with a score of
111 * @return All trusted identities
112 * @throws PluginException
113 * if an error occured talking to the Web of Trust plugin
115 public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity) throws PluginException {
116 return loadTrustedIdentities(ownIdentity, null);
120 * Loads all identities that the given identities trusts with a score of
121 * more than 0 and the (optional) given context.
126 * The context to filter, or {@code null}
127 * @return All trusted identities
128 * @throws PluginException
129 * if an error occured talking to the Web of Trust plugin
131 public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity, String context) throws PluginException {
132 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentitiesByScore").put("Truster", ownIdentity.getId()).put("Selection", "+").put("Context", (context == null) ? "" : context).put("WantTrustValues", "true").get());
133 SimpleFieldSet fields = reply.getFields();
134 Set<Identity> identities = new HashSet<Identity>();
135 int identityCounter = -1;
137 String id = fields.get("Identity" + ++identityCounter);
141 String nickname = fields.get("Nickname" + identityCounter);
142 String requestUri = fields.get("RequestURI" + identityCounter);
143 DefaultIdentity identity = new DefaultIdentity(id, nickname, requestUri);
144 identity.setContexts(parseContexts("Contexts" + identityCounter + ".", fields));
145 identity.setProperties(parseProperties("Properties" + identityCounter + ".", fields));
146 Integer trust = Numbers.safeParseInteger(fields.get("Trust" + identityCounter), null);
147 int score = Numbers.safeParseInteger(fields.get("Score" + identityCounter), 0);
148 int rank = Numbers.safeParseInteger(fields.get("Rank" + identityCounter), 0);
149 identity.setTrust(ownIdentity, new Trust(trust, score, rank));
150 identities.add(identity);
156 * Adds the given context to the given identity.
159 * The identity to add the context to
162 * @throws PluginException
163 * if an error occured talking to the Web of Trust plugin
165 public void addContext(OwnIdentity ownIdentity, String context) throws PluginException {
166 performRequest(SimpleFieldSetConstructor.create().put("Message", "AddContext").put("Identity", ownIdentity.getId()).put("Context", context).get());
170 * Removes the given context from the given identity.
173 * The identity to remove the context from
175 * The context to remove
176 * @throws PluginException
177 * if an error occured talking to the Web of Trust plugin
179 public void removeContext(OwnIdentity ownIdentity, String context) throws PluginException {
180 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveContext").put("Identity", ownIdentity.getId()).put("Context", context).get());
184 * Returns the value of the property with the given name.
187 * The identity whose properties to check
189 * The name of the property to return
190 * @return The value of the property, or {@code null} if there is no value
191 * @throws PluginException
192 * if an error occured talking to the Web of Trust plugin
194 public String getProperty(Identity identity, String name) throws PluginException {
195 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetProperty").put("Identity", identity.getId()).put("Property", name).get());
196 return reply.getFields().get("Property");
200 * Sets the property with the given name to the given value.
203 * The identity to set the property on
205 * The name of the property to set
208 * @throws PluginException
209 * if an error occured talking to the Web of Trust plugin
211 public void setProperty(OwnIdentity ownIdentity, String name, String value) throws PluginException {
212 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetProperty").put("Identity", ownIdentity.getId()).put("Property", name).put("Value", value).get());
216 * Removes the property with the given name.
219 * The identity to remove the property from
221 * The name of the property to remove
222 * @throws PluginException
223 * if an error occured talking to the Web of Trust plugin
225 public void removeProperty(OwnIdentity ownIdentity, String name) throws PluginException {
226 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveProperty").put("Identity", ownIdentity.getId()).put("Property", name).get());
230 * Returns the trust for the given identity assigned to it by the given own
236 * The identity to get the trust for
237 * @return The trust for the given identity
238 * @throws PluginException
239 * if an error occured talking to the Web of Trust plugin
241 public Trust getTrust(OwnIdentity ownIdentity, Identity identity) throws PluginException {
242 Reply getTrustReply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentity").put("Truster", ownIdentity.getId()).put("Identity", identity.getId()).get());
243 String trust = getTrustReply.getFields().get("Trust");
244 String score = getTrustReply.getFields().get("Score");
245 String rank = getTrustReply.getFields().get("Rank");
246 Integer explicit = null;
247 Integer implicit = null;
248 Integer distance = null;
250 explicit = Integer.valueOf(trust);
251 } catch (NumberFormatException nfe1) {
255 implicit = Integer.valueOf(score);
256 distance = Integer.valueOf(rank);
257 } catch (NumberFormatException nfe1) {
260 return new Trust(explicit, implicit, distance);
264 * Sets the trust for the given identity.
267 * The trusting identity
269 * The trusted identity
271 * The amount of trust (-100 thru 100)
273 * The comment or explanation of the trust value
274 * @throws PluginException
275 * if an error occured talking to the Web of Trust plugin
277 public void setTrust(OwnIdentity ownIdentity, Identity identity, int trust, String comment) throws PluginException {
278 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).put("Value", String.valueOf(trust)).put("Comment", comment).get());
282 * Removes any trust assignment of the given own identity for the given
288 * The identity to remove all trust for
289 * @throws WebOfTrustException
292 public void removeTrust(OwnIdentity ownIdentity, Identity identity) throws WebOfTrustException {
293 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).get());
297 * Pings the Web of Trust plugin. If the plugin can not be reached, a
298 * {@link PluginException} is thrown.
300 * @throws PluginException
301 * if the plugin is not loaded
303 public void ping() throws PluginException {
304 performRequest(SimpleFieldSetConstructor.create().put("Message", "Ping").get());
312 * Parses the contexts from the given fields.
315 * The prefix to use to access the contexts
317 * The fields to parse the contexts from
318 * @return The parsed contexts
320 private static Set<String> parseContexts(String prefix, SimpleFieldSet fields) {
321 Set<String> contexts = new HashSet<String>();
322 int contextCounter = -1;
324 String context = fields.get(prefix + "Context" + ++contextCounter);
325 if (context == null) {
328 contexts.add(context);
334 * Parses the properties from the given fields.
337 * The prefix to use to access the properties
339 * The fields to parse the properties from
340 * @return The parsed properties
342 private static Map<String, String> parseProperties(String prefix, SimpleFieldSet fields) {
343 Map<String, String> properties = new HashMap<String, String>();
344 int propertiesCounter = -1;
346 String propertyName = fields.get(prefix + "Property" + ++propertiesCounter + ".Name");
347 if (propertyName == null) {
350 String propertyValue = fields.get(prefix + "Property" + propertiesCounter + ".Value");
351 properties.put(propertyName, propertyValue);
357 * Sends a request containing the given fields and waits for the target
361 * The fields of the message
362 * @return The reply message
363 * @throws PluginException
364 * if the request could not be sent
366 private Reply performRequest(SimpleFieldSet fields) throws PluginException {
367 return performRequest(fields, null);
371 * Sends a request containing the given fields and waits for the target
375 * The fields of the message
377 * The payload of the message
378 * @return The reply message
379 * @throws PluginException
380 * if the request could not be sent
382 private Reply performRequest(SimpleFieldSet fields, Bucket data) throws PluginException {
383 final String identifier = "FCP-Command-" + System.currentTimeMillis() + "-" + counter.getAndIncrement();
384 final Reply reply = new Reply();
385 logger.log(Level.FINE, String.format("Sending FCP Request: %s", fields.get("Message")));
386 ConnectorListener connectorListener = new ConnectorListener() {
389 @SuppressWarnings("synthetic-access")
390 public void receivedReply(PluginConnector pluginConnector, SimpleFieldSet fields, Bucket data) {
391 String messageName = fields.get("Message");
392 logger.log(Level.FINEST, String.format("Received Reply from Plugin: %s", messageName));
393 synchronized (reply) {
394 reply.setFields(fields);
400 pluginConnector.addConnectorListener(WOT_PLUGIN_NAME, identifier, connectorListener);
401 synchronized (reply) {
403 pluginConnector.sendRequest(WOT_PLUGIN_NAME, identifier, fields, data);
404 while (reply.getFields() == null) {
407 } catch (InterruptedException ie1) {
408 logger.log(Level.WARNING, String.format("Got interrupted while waiting for reply on %s.", fields.get("Message")), ie1);
412 pluginConnector.removeConnectorListener(WOT_PLUGIN_NAME, identifier, connectorListener);
415 logger.log(Level.FINEST, String.format("Received FCP Response for %s: %s", fields.get("Message"), (reply.getFields() != null) ? reply.getFields().get("Message") : null));
416 if ((reply.getFields() == null) || "Error".equals(reply.getFields().get("Message"))) {
417 throw new PluginException("Could not perform request for " + fields.get("Message"));
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;