2 * Sone - WebOfTrustConnector.java - Copyright © 2010–2013 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.PluginConnector;
29 import net.pterodactylus.sone.freenet.plugin.PluginException;
30 import net.pterodactylus.sone.freenet.plugin.event.ReceivedReplyEvent;
31 import net.pterodactylus.util.logging.Logging;
32 import net.pterodactylus.util.number.Numbers;
34 import com.google.common.base.Optional;
35 import com.google.common.collect.MapMaker;
36 import com.google.common.eventbus.Subscribe;
37 import com.google.inject.Inject;
39 import freenet.support.SimpleFieldSet;
40 import freenet.support.api.Bucket;
43 * Connector for the Web of Trust plugin.
45 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
47 public class WebOfTrustConnector {
50 private static final Logger logger = Logging.getLogger(WebOfTrustConnector.class);
52 /** The name of the WoT plugin. */
53 private static final String WOT_PLUGIN_NAME = "plugins.WebOfTrust.WebOfTrust";
55 /** Counter for connection identifiers. */
56 private final AtomicLong counter = new AtomicLong();
58 /** The plugin connector. */
59 private final PluginConnector pluginConnector;
61 /** Map for replies. */
62 private final Map<PluginIdentifier, Reply> replies = new MapMaker().makeMap();
65 * Creates a new Web of Trust connector that uses the given plugin
68 * @param pluginConnector
69 * The plugin connector
72 public WebOfTrustConnector(PluginConnector pluginConnector) {
73 this.pluginConnector = pluginConnector;
81 * Stops the web of trust connector.
88 * Loads all own identities from the Web of Trust plugin.
90 * @return All own identity
91 * @throws WebOfTrustException
92 * if the own identities can not be loaded
94 public Set<OwnIdentity> loadAllOwnIdentities() throws WebOfTrustException {
95 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetOwnIdentities").get());
96 SimpleFieldSet fields = reply.getFields();
97 int ownIdentityCounter = -1;
98 Set<OwnIdentity> ownIdentities = new HashSet<OwnIdentity>();
100 String id = fields.get("Identity" + ++ownIdentityCounter);
104 String requestUri = fields.get("RequestURI" + ownIdentityCounter);
105 String insertUri = fields.get("InsertURI" + ownIdentityCounter);
106 String nickname = fields.get("Nickname" + ownIdentityCounter);
107 DefaultOwnIdentity ownIdentity = new DefaultOwnIdentity(id, nickname, requestUri, insertUri);
108 ownIdentity.setContexts(parseContexts("Contexts" + ownIdentityCounter + ".", fields));
109 ownIdentity.setProperties(parseProperties("Properties" + ownIdentityCounter + ".", fields));
110 ownIdentities.add(ownIdentity);
112 return ownIdentities;
116 * Loads all identities that the given identities trusts with a score of
121 * @return All trusted identities
122 * @throws PluginException
123 * if an error occured talking to the Web of Trust plugin
125 public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity) throws PluginException {
126 return loadTrustedIdentities(ownIdentity, null);
130 * Loads all identities that the given identities trusts with a score of
131 * more than 0 and the (optional) given context.
136 * The context to filter, or {@code null}
137 * @return All trusted identities
138 * @throws PluginException
139 * if an error occured talking to the Web of Trust plugin
141 public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity, Optional<String> context) throws PluginException {
142 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentitiesByScore").put("Truster", ownIdentity.getId()).put("Selection", "+").put("Context", context.or("")).put("WantTrustValues", "true").get());
143 SimpleFieldSet fields = reply.getFields();
144 Set<Identity> identities = new HashSet<Identity>();
145 int identityCounter = -1;
147 String id = fields.get("Identity" + ++identityCounter);
151 String nickname = fields.get("Nickname" + identityCounter);
152 String requestUri = fields.get("RequestURI" + identityCounter);
153 DefaultIdentity identity = new DefaultIdentity(id, nickname, requestUri);
154 identity.setContexts(parseContexts("Contexts" + identityCounter + ".", fields));
155 identity.setProperties(parseProperties("Properties" + identityCounter + ".", fields));
156 Integer trust = Numbers.safeParseInteger(fields.get("Trust" + identityCounter), null);
157 int score = Numbers.safeParseInteger(fields.get("Score" + identityCounter), 0);
158 int rank = Numbers.safeParseInteger(fields.get("Rank" + identityCounter), 0);
159 identity.setTrust(ownIdentity, new Trust(trust, score, rank));
160 identities.add(identity);
166 * Adds the given context to the given identity.
169 * The identity to add the context to
172 * @throws PluginException
173 * if an error occured talking to the Web of Trust plugin
175 public void addContext(OwnIdentity ownIdentity, String context) throws PluginException {
176 performRequest(SimpleFieldSetConstructor.create().put("Message", "AddContext").put("Identity", ownIdentity.getId()).put("Context", context).get());
180 * Removes the given context from the given identity.
183 * The identity to remove the context from
185 * The context to remove
186 * @throws PluginException
187 * if an error occured talking to the Web of Trust plugin
189 public void removeContext(OwnIdentity ownIdentity, String context) throws PluginException {
190 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveContext").put("Identity", ownIdentity.getId()).put("Context", context).get());
194 * Returns the value of the property with the given name.
197 * The identity whose properties to check
199 * The name of the property to return
200 * @return The value of the property, or {@code null} if there is no value
201 * @throws PluginException
202 * if an error occured talking to the Web of Trust plugin
204 public String getProperty(Identity identity, String name) throws PluginException {
205 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetProperty").put("Identity", identity.getId()).put("Property", name).get());
206 return reply.getFields().get("Property");
210 * Sets the property with the given name to the given value.
213 * The identity to set the property on
215 * The name of the property to set
218 * @throws PluginException
219 * if an error occured talking to the Web of Trust plugin
221 public void setProperty(OwnIdentity ownIdentity, String name, String value) throws PluginException {
222 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetProperty").put("Identity", ownIdentity.getId()).put("Property", name).put("Value", value).get());
226 * Removes the property with the given name.
229 * The identity to remove the property from
231 * The name of the property to remove
232 * @throws PluginException
233 * if an error occured talking to the Web of Trust plugin
235 public void removeProperty(OwnIdentity ownIdentity, String name) throws PluginException {
236 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveProperty").put("Identity", ownIdentity.getId()).put("Property", name).get());
240 * Returns the trust for the given identity assigned to it by the given own
246 * The identity to get the trust for
247 * @return The trust for the given identity
248 * @throws PluginException
249 * if an error occured talking to the Web of Trust plugin
251 public Trust getTrust(OwnIdentity ownIdentity, Identity identity) throws PluginException {
252 Reply getTrustReply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentity").put("Truster", ownIdentity.getId()).put("Identity", identity.getId()).get());
253 String trust = getTrustReply.getFields().get("Trust");
254 String score = getTrustReply.getFields().get("Score");
255 String rank = getTrustReply.getFields().get("Rank");
256 Integer explicit = null;
257 Integer implicit = null;
258 Integer distance = null;
260 explicit = Integer.valueOf(trust);
261 } catch (NumberFormatException nfe1) {
265 implicit = Integer.valueOf(score);
266 distance = Integer.valueOf(rank);
267 } catch (NumberFormatException nfe1) {
270 return new Trust(explicit, implicit, distance);
274 * Sets the trust for the given identity.
277 * The trusting identity
279 * The trusted identity
281 * The amount of trust (-100 thru 100)
283 * The comment or explanation of the trust value
284 * @throws PluginException
285 * if an error occured talking to the Web of Trust plugin
287 public void setTrust(OwnIdentity ownIdentity, Identity identity, int trust, String comment) throws PluginException {
288 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).put("Value", String.valueOf(trust)).put("Comment", comment).get());
292 * Removes any trust assignment of the given own identity for the given
298 * The identity to remove all trust for
299 * @throws WebOfTrustException
302 public void removeTrust(OwnIdentity ownIdentity, Identity identity) throws WebOfTrustException {
303 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).get());
307 * Pings the Web of Trust plugin. If the plugin can not be reached, a
308 * {@link PluginException} is thrown.
310 * @throws PluginException
311 * if the plugin is not loaded
313 public void ping() throws PluginException {
314 performRequest(SimpleFieldSetConstructor.create().put("Message", "Ping").get());
322 * Parses the contexts from the given fields.
325 * The prefix to use to access the contexts
327 * The fields to parse the contexts from
328 * @return The parsed contexts
330 private static Set<String> parseContexts(String prefix, SimpleFieldSet fields) {
331 Set<String> contexts = new HashSet<String>();
332 int contextCounter = -1;
334 String context = fields.get(prefix + "Context" + ++contextCounter);
335 if (context == null) {
338 contexts.add(context);
344 * Parses the properties from the given fields.
347 * The prefix to use to access the properties
349 * The fields to parse the properties from
350 * @return The parsed properties
352 private static Map<String, String> parseProperties(String prefix, SimpleFieldSet fields) {
353 Map<String, String> properties = new HashMap<String, String>();
354 int propertiesCounter = -1;
356 String propertyName = fields.get(prefix + "Property" + ++propertiesCounter + ".Name");
357 if (propertyName == null) {
360 String propertyValue = fields.get(prefix + "Property" + propertiesCounter + ".Value");
361 properties.put(propertyName, propertyValue);
367 * Sends a request containing the given fields and waits for the target
371 * The fields of the message
372 * @return The reply message
373 * @throws PluginException
374 * if the request could not be sent
376 private Reply performRequest(SimpleFieldSet fields) throws PluginException {
377 return performRequest(fields, null);
381 * Sends a request containing the given fields and waits for the target
385 * The fields of the message
387 * The payload of the message
388 * @return The reply message
389 * @throws PluginException
390 * if the request could not be sent
392 private Reply performRequest(SimpleFieldSet fields, Bucket data) throws PluginException {
393 String identifier = "FCP-Command-" + System.currentTimeMillis() + "-" + counter.getAndIncrement();
394 Reply reply = new Reply();
395 PluginIdentifier pluginIdentifier = new PluginIdentifier(WOT_PLUGIN_NAME, identifier);
396 replies.put(pluginIdentifier, reply);
398 logger.log(Level.FINE, String.format("Sending FCP Request: %s", fields.get("Message")));
399 synchronized (reply) {
401 pluginConnector.sendRequest(WOT_PLUGIN_NAME, identifier, fields, data);
402 while (reply.getFields() == null) {
405 } catch (InterruptedException ie1) {
406 logger.log(Level.WARNING, String.format("Got interrupted while waiting for reply on %s.", fields.get("Message")), ie1);
410 replies.remove(pluginIdentifier);
413 logger.log(Level.FINEST, String.format("Received FCP Response for %s: %s", fields.get("Message"), (reply.getFields() != null) ? reply.getFields().get("Message") : null));
414 if ((reply.getFields() == null) || "Error".equals(reply.getFields().get("Message"))) {
415 throw new PluginException("Could not perform request for " + fields.get("Message"));
421 * Notifies the connector that a plugin reply was received.
423 * @param receivedReplyEvent
427 public void receivedReply(ReceivedReplyEvent receivedReplyEvent) {
428 PluginIdentifier pluginIdentifier = new PluginIdentifier(receivedReplyEvent.pluginName(), receivedReplyEvent.identifier());
429 Reply reply = replies.remove(pluginIdentifier);
433 logger.log(Level.FINEST, String.format("Received Reply from Plugin: %s", receivedReplyEvent.fieldSet().get("Message")));
434 synchronized (reply) {
435 reply.setFields(receivedReplyEvent.fieldSet());
436 reply.setData(receivedReplyEvent.data());
442 * Container for the data of the reply from a plugin.
444 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
446 private static class Reply {
448 /** The fields of the reply. */
449 private SimpleFieldSet fields;
451 /** The payload of the reply. */
454 /** Empty constructor. */
460 * Returns the fields of the reply.
462 * @return The fields of the reply
464 public SimpleFieldSet getFields() {
469 * Sets the fields of the reply.
472 * The fields of the reply
474 public void setFields(SimpleFieldSet fields) {
475 this.fields = fields;
479 * Returns the payload of the reply.
481 * @return The payload of the reply (may be {@code null})
483 @SuppressWarnings("unused")
484 public Bucket getData() {
489 * Sets the payload of the reply.
492 * The payload of the reply (may be {@code null})
494 public void setData(Bucket data) {
501 * Helper method to create {@link SimpleFieldSet}s with terser code.
503 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
505 private static class SimpleFieldSetConstructor {
507 /** The field set being created. */
508 private SimpleFieldSet simpleFieldSet;
511 * Creates a new simple field set constructor.
514 * {@code true} if the resulting simple field set should be
515 * short-lived, {@code false} otherwise
517 private SimpleFieldSetConstructor(boolean shortLived) {
518 simpleFieldSet = new SimpleFieldSet(shortLived);
526 * Returns the created simple field set.
528 * @return The created simple field set
530 public SimpleFieldSet get() {
531 return simpleFieldSet;
535 * Sets the field with the given name to the given value.
538 * The name of the fleld
540 * The value of the field
541 * @return This constructor (for method chaining)
543 public SimpleFieldSetConstructor put(String name, String value) {
544 simpleFieldSet.putOverwrite(name, value);
553 * Creates a new simple field set constructor.
555 * @return The created simple field set constructor
557 public static SimpleFieldSetConstructor create() {
562 * Creates a new simple field set constructor.
565 * {@code true} if the resulting simple field set should be
566 * short-lived, {@code false} otherwise
567 * @return The created simple field set constructor
569 public static SimpleFieldSetConstructor create(boolean shortLived) {
570 return new SimpleFieldSetConstructor(shortLived);
576 * Container for identifying plugins. Plugins are identified by their plugin
577 * name and their unique identifier.
579 * @author <a href="mailto:d.roden@xplosion.de">David Roden</a>
581 private static class PluginIdentifier {
583 /** The plugin name. */
584 private final String pluginName;
586 /** The plugin identifier. */
587 private final String identifier;
590 * Creates a new plugin identifier.
593 * The name of the plugin
595 * The identifier of the plugin
597 public PluginIdentifier(String pluginName, String identifier) {
598 this.pluginName = pluginName;
599 this.identifier = identifier;
610 public int hashCode() {
611 return pluginName.hashCode() ^ identifier.hashCode();
618 public boolean equals(Object object) {
619 if (!(object instanceof PluginIdentifier)) {
622 PluginIdentifier pluginIdentifier = (PluginIdentifier) object;
623 return pluginName.equals(pluginIdentifier.pluginName) && identifier.equals(pluginIdentifier.identifier);