2 * Sone - WebOfTrustConnector.java - Copyright © 2010–2015 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 static java.util.logging.Logger.getLogger;
21 import static net.pterodactylus.sone.utils.NumberParsers.parseInt;
23 import java.util.HashMap;
24 import java.util.HashSet;
27 import java.util.concurrent.atomic.AtomicLong;
28 import java.util.logging.Level;
29 import java.util.logging.Logger;
31 import net.pterodactylus.sone.freenet.plugin.PluginConnector;
32 import net.pterodactylus.sone.freenet.plugin.PluginException;
33 import net.pterodactylus.sone.freenet.plugin.event.ReceivedReplyEvent;
35 import com.google.common.base.Optional;
36 import com.google.common.collect.MapMaker;
37 import com.google.common.eventbus.Subscribe;
38 import com.google.inject.Inject;
39 import com.google.inject.Singleton;
41 import freenet.support.SimpleFieldSet;
42 import freenet.support.api.Bucket;
45 * Connector for the Web of Trust plugin.
47 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
50 public class WebOfTrustConnector {
53 private static final Logger logger = getLogger(WebOfTrustConnector.class.getName());
55 /** The name of the WoT plugin. */
56 private static final String WOT_PLUGIN_NAME = "plugins.WebOfTrust.WebOfTrust";
58 /** Counter for connection identifiers. */
59 private final AtomicLong counter = new AtomicLong();
61 /** The plugin connector. */
62 private final PluginConnector pluginConnector;
64 /** Map for replies. */
65 private final Map<PluginIdentifier, Reply> replies = new MapMaker().makeMap();
68 * Creates a new Web of Trust connector that uses the given plugin
71 * @param pluginConnector
72 * The plugin connector
75 public WebOfTrustConnector(PluginConnector pluginConnector) {
76 this.pluginConnector = pluginConnector;
85 pluginConnector.start();
86 } catch (PluginException e) {
92 * Stops the web of trust connector.
99 * Loads all own identities from the Web of Trust plugin.
101 * @return All own identity
102 * @throws WebOfTrustException
103 * if the own identities can not be loaded
105 public Set<OwnIdentity> loadAllOwnIdentities() throws WebOfTrustException {
106 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetOwnIdentities").get());
107 SimpleFieldSet fields = reply.getFields();
108 int ownIdentityCounter = -1;
109 Set<OwnIdentity> ownIdentities = new HashSet<OwnIdentity>();
111 String id = fields.get("Identity" + ++ownIdentityCounter);
115 String requestUri = fields.get("RequestURI" + ownIdentityCounter);
116 String insertUri = fields.get("InsertURI" + ownIdentityCounter);
117 String nickname = fields.get("Nickname" + ownIdentityCounter);
118 DefaultOwnIdentity ownIdentity = new DefaultOwnIdentity(id, nickname, requestUri, insertUri);
119 ownIdentity.setContexts(parseContexts("Contexts" + ownIdentityCounter + ".", fields));
120 ownIdentity.setProperties(parseProperties("Properties" + ownIdentityCounter + ".", fields));
121 ownIdentities.add(ownIdentity);
123 return ownIdentities;
127 * Loads all identities that the given identities trusts with a score of
132 * @return All trusted identities
133 * @throws PluginException
134 * if an error occured talking to the Web of Trust plugin
136 public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity) throws PluginException {
137 return loadTrustedIdentities(ownIdentity, Optional.<String>absent());
141 * Loads all identities that the given identities trusts with a score of
142 * more than 0 and the (optional) given context.
147 * The context to filter, or {@code null}
148 * @return All trusted identities
149 * @throws PluginException
150 * if an error occured talking to the Web of Trust plugin
152 public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity, Optional<String> context) throws PluginException {
153 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentitiesByScore").put("Truster", ownIdentity.getId()).put("Selection", "+").put("Context", context.or("")).put("WantTrustValues", "true").get());
154 SimpleFieldSet fields = reply.getFields();
155 Set<Identity> identities = new HashSet<Identity>();
156 int identityCounter = -1;
158 String id = fields.get("Identity" + ++identityCounter);
162 String nickname = fields.get("Nickname" + identityCounter);
163 String requestUri = fields.get("RequestURI" + identityCounter);
164 DefaultIdentity identity = new DefaultIdentity(id, nickname, requestUri);
165 identity.setContexts(parseContexts("Contexts" + identityCounter + ".", fields));
166 identity.setProperties(parseProperties("Properties" + identityCounter + ".", fields));
167 Integer trust = parseInt(fields.get("Trust" + identityCounter), null);
168 int score = parseInt(fields.get("Score" + identityCounter), 0);
169 int rank = parseInt(fields.get("Rank" + identityCounter), 0);
170 identity.setTrust(ownIdentity, new Trust(trust, score, rank));
171 identities.add(identity);
177 * Adds the given context to the given identity.
180 * The identity to add the context to
183 * @throws PluginException
184 * if an error occured talking to the Web of Trust plugin
186 public void addContext(OwnIdentity ownIdentity, String context) throws PluginException {
187 performRequest(SimpleFieldSetConstructor.create().put("Message", "AddContext").put("Identity", ownIdentity.getId()).put("Context", context).get());
191 * Removes the given context from the given identity.
194 * The identity to remove the context from
196 * The context to remove
197 * @throws PluginException
198 * if an error occured talking to the Web of Trust plugin
200 public void removeContext(OwnIdentity ownIdentity, String context) throws PluginException {
201 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveContext").put("Identity", ownIdentity.getId()).put("Context", context).get());
205 * Returns the value of the property with the given name.
208 * The identity whose properties to check
210 * The name of the property to return
211 * @return The value of the property, or {@code null} if there is no value
212 * @throws PluginException
213 * if an error occured talking to the Web of Trust plugin
215 public String getProperty(Identity identity, String name) throws PluginException {
216 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetProperty").put("Identity", identity.getId()).put("Property", name).get());
217 return reply.getFields().get("Property");
221 * Sets the property with the given name to the given value.
224 * The identity to set the property on
226 * The name of the property to set
229 * @throws PluginException
230 * if an error occured talking to the Web of Trust plugin
232 public void setProperty(OwnIdentity ownIdentity, String name, String value) throws PluginException {
233 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetProperty").put("Identity", ownIdentity.getId()).put("Property", name).put("Value", value).get());
237 * Removes the property with the given name.
240 * The identity to remove the property from
242 * The name of the property to remove
243 * @throws PluginException
244 * if an error occured talking to the Web of Trust plugin
246 public void removeProperty(OwnIdentity ownIdentity, String name) throws PluginException {
247 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveProperty").put("Identity", ownIdentity.getId()).put("Property", name).get());
251 * Returns the trust for the given identity assigned to it by the given own
257 * The identity to get the trust for
258 * @return The trust for the given identity
259 * @throws PluginException
260 * if an error occured talking to the Web of Trust plugin
262 public Trust getTrust(OwnIdentity ownIdentity, Identity identity) throws PluginException {
263 Reply getTrustReply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentity").put("Truster", ownIdentity.getId()).put("Identity", identity.getId()).get());
264 String trust = getTrustReply.getFields().get("Trust");
265 String score = getTrustReply.getFields().get("Score");
266 String rank = getTrustReply.getFields().get("Rank");
267 Integer explicit = null;
268 Integer implicit = null;
269 Integer distance = null;
271 explicit = Integer.valueOf(trust);
272 } catch (NumberFormatException nfe1) {
276 implicit = Integer.valueOf(score);
277 distance = Integer.valueOf(rank);
278 } catch (NumberFormatException nfe1) {
281 return new Trust(explicit, implicit, distance);
285 * Sets the trust for the given identity.
288 * The trusting identity
290 * The trusted identity
292 * The amount of trust (-100 thru 100)
294 * The comment or explanation of the trust value
295 * @throws PluginException
296 * if an error occured talking to the Web of Trust plugin
298 public void setTrust(OwnIdentity ownIdentity, Identity identity, int trust, String comment) throws PluginException {
299 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).put("Value", String.valueOf(trust)).put("Comment", comment).get());
303 * Removes any trust assignment of the given own identity for the given
309 * The identity to remove all trust for
310 * @throws WebOfTrustException
313 public void removeTrust(OwnIdentity ownIdentity, Identity identity) throws WebOfTrustException {
314 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).get());
318 * Pings the Web of Trust plugin. If the plugin can not be reached, a
319 * {@link PluginException} is thrown.
321 * @throws PluginException
322 * if the plugin is not loaded
324 public void ping() throws PluginException {
325 performRequest(SimpleFieldSetConstructor.create().put("Message", "Ping").get());
333 * Parses the contexts from the given fields.
336 * The prefix to use to access the contexts
338 * The fields to parse the contexts from
339 * @return The parsed contexts
341 private static Set<String> parseContexts(String prefix, SimpleFieldSet fields) {
342 Set<String> contexts = new HashSet<String>();
343 int contextCounter = -1;
345 String context = fields.get(prefix + "Context" + ++contextCounter);
346 if (context == null) {
349 contexts.add(context);
355 * Parses the properties from the given fields.
358 * The prefix to use to access the properties
360 * The fields to parse the properties from
361 * @return The parsed properties
363 private static Map<String, String> parseProperties(String prefix, SimpleFieldSet fields) {
364 Map<String, String> properties = new HashMap<String, String>();
365 int propertiesCounter = -1;
367 String propertyName = fields.get(prefix + "Property" + ++propertiesCounter + ".Name");
368 if (propertyName == null) {
371 String propertyValue = fields.get(prefix + "Property" + propertiesCounter + ".Value");
372 properties.put(propertyName, propertyValue);
378 * Sends a request containing the given fields and waits for the target
382 * The fields of the message
383 * @return The reply message
384 * @throws PluginException
385 * if the request could not be sent
387 private Reply performRequest(SimpleFieldSet fields) throws PluginException {
388 return performRequest(fields, null);
392 * Sends a request containing the given fields and waits for the target
396 * The fields of the message
398 * The payload of the message
399 * @return The reply message
400 * @throws PluginException
401 * if the request could not be sent
403 private Reply performRequest(SimpleFieldSet fields, Bucket data) throws PluginException {
404 String identifier = "FCP-Command-" + System.currentTimeMillis() + "-" + counter.getAndIncrement();
405 Reply reply = new Reply();
406 PluginIdentifier pluginIdentifier = new PluginIdentifier(WOT_PLUGIN_NAME, identifier);
407 replies.put(pluginIdentifier, reply);
409 logger.log(Level.FINE, String.format("Sending FCP Request: %s", fields.get("Message")));
410 synchronized (reply) {
412 pluginConnector.sendRequest(WOT_PLUGIN_NAME, identifier, fields, data);
413 while (reply.getFields() == null) {
416 } catch (InterruptedException ie1) {
417 logger.log(Level.WARNING, String.format("Got interrupted while waiting for reply on %s.", fields.get("Message")), ie1);
421 replies.remove(pluginIdentifier);
424 logger.log(Level.FINEST, String.format("Received FCP Response for %s: %s", fields.get("Message"), (reply.getFields() != null) ? reply.getFields().get("Message") : null));
425 if ((reply.getFields() == null) || "Error".equals(reply.getFields().get("Message"))) {
426 throw new PluginException("Could not perform request for " + fields.get("Message"));
432 * Notifies the connector that a plugin reply was received.
434 * @param receivedReplyEvent
438 public void receivedReply(ReceivedReplyEvent receivedReplyEvent) {
439 PluginIdentifier pluginIdentifier = new PluginIdentifier(receivedReplyEvent.pluginName(), receivedReplyEvent.identifier());
440 Reply reply = replies.remove(pluginIdentifier);
444 logger.log(Level.FINEST, String.format("Received Reply from Plugin: %s", receivedReplyEvent.fieldSet().get("Message")));
445 synchronized (reply) {
446 reply.setFields(receivedReplyEvent.fieldSet());
447 reply.setData(receivedReplyEvent.data());
453 * Container for the data of the reply from a plugin.
455 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
457 private static class Reply {
459 /** The fields of the reply. */
460 private SimpleFieldSet fields;
462 /** The payload of the reply. */
465 /** Empty constructor. */
471 * Returns the fields of the reply.
473 * @return The fields of the reply
475 public SimpleFieldSet getFields() {
480 * Sets the fields of the reply.
483 * The fields of the reply
485 public void setFields(SimpleFieldSet fields) {
486 this.fields = fields;
490 * Returns the payload of the reply.
492 * @return The payload of the reply (may be {@code null})
494 @SuppressWarnings("unused")
495 public Bucket getData() {
500 * Sets the payload of the reply.
503 * The payload of the reply (may be {@code null})
505 public void setData(Bucket data) {
512 * Helper method to create {@link SimpleFieldSet}s with terser code.
514 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
516 private static class SimpleFieldSetConstructor {
518 /** The field set being created. */
519 private SimpleFieldSet simpleFieldSet;
522 * Creates a new simple field set constructor.
525 * {@code true} if the resulting simple field set should be
526 * short-lived, {@code false} otherwise
528 private SimpleFieldSetConstructor(boolean shortLived) {
529 simpleFieldSet = new SimpleFieldSet(shortLived);
537 * Returns the created simple field set.
539 * @return The created simple field set
541 public SimpleFieldSet get() {
542 return simpleFieldSet;
546 * Sets the field with the given name to the given value.
549 * The name of the fleld
551 * The value of the field
552 * @return This constructor (for method chaining)
554 public SimpleFieldSetConstructor put(String name, String value) {
555 simpleFieldSet.putOverwrite(name, value);
564 * Creates a new simple field set constructor.
566 * @return The created simple field set constructor
568 public static SimpleFieldSetConstructor create() {
573 * Creates a new simple field set constructor.
576 * {@code true} if the resulting simple field set should be
577 * short-lived, {@code false} otherwise
578 * @return The created simple field set constructor
580 public static SimpleFieldSetConstructor create(boolean shortLived) {
581 return new SimpleFieldSetConstructor(shortLived);
587 * Container for identifying plugins. Plugins are identified by their plugin
588 * name and their unique identifier.
590 * @author <a href="mailto:d.roden@xplosion.de">David Roden</a>
592 private static class PluginIdentifier {
594 /** The plugin name. */
595 private final String pluginName;
597 /** The plugin identifier. */
598 private final String identifier;
601 * Creates a new plugin identifier.
604 * The name of the plugin
606 * The identifier of the plugin
608 public PluginIdentifier(String pluginName, String identifier) {
609 this.pluginName = pluginName;
610 this.identifier = identifier;
621 public int hashCode() {
622 return pluginName.hashCode() ^ identifier.hashCode();
629 public boolean equals(Object object) {
630 if (!(object instanceof PluginIdentifier)) {
633 PluginIdentifier pluginIdentifier = (PluginIdentifier) object;
634 return pluginName.equals(pluginIdentifier.pluginName) && identifier.equals(pluginIdentifier.identifier);