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;
38 import com.google.inject.Singleton;
40 import freenet.support.SimpleFieldSet;
41 import freenet.support.api.Bucket;
44 * Connector for the Web of Trust plugin.
46 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
49 public class WebOfTrustConnector {
52 private static final Logger logger = Logging.getLogger(WebOfTrustConnector.class);
54 /** The name of the WoT plugin. */
55 private static final String WOT_PLUGIN_NAME = "plugins.WebOfTrust.WebOfTrust";
57 /** Counter for connection identifiers. */
58 private final AtomicLong counter = new AtomicLong();
60 /** The plugin connector. */
61 private final PluginConnector pluginConnector;
63 /** Map for replies. */
64 private final Map<PluginIdentifier, Reply> replies = new MapMaker().makeMap();
67 * Creates a new Web of Trust connector that uses the given plugin
70 * @param pluginConnector
71 * The plugin connector
74 public WebOfTrustConnector(PluginConnector pluginConnector) {
75 this.pluginConnector = pluginConnector;
83 * Stops the web of trust connector.
90 * Loads all own identities from the Web of Trust plugin.
92 * @return All own identity
93 * @throws WebOfTrustException
94 * if the own identities can not be loaded
96 public Set<OwnIdentity> loadAllOwnIdentities() throws WebOfTrustException {
97 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetOwnIdentities").get());
98 SimpleFieldSet fields = reply.getFields();
99 int ownIdentityCounter = -1;
100 Set<OwnIdentity> ownIdentities = new HashSet<OwnIdentity>();
102 String id = fields.get("Identity" + ++ownIdentityCounter);
106 String requestUri = fields.get("RequestURI" + ownIdentityCounter);
107 String insertUri = fields.get("InsertURI" + ownIdentityCounter);
108 String nickname = fields.get("Nickname" + ownIdentityCounter);
109 DefaultOwnIdentity ownIdentity = new DefaultOwnIdentity(id, nickname, requestUri, insertUri);
110 ownIdentity.setContexts(parseContexts("Contexts" + ownIdentityCounter + ".", fields));
111 ownIdentity.setProperties(parseProperties("Properties" + ownIdentityCounter + ".", fields));
112 ownIdentities.add(ownIdentity);
114 return ownIdentities;
118 * Loads all identities that the given identities trusts with a score of
123 * @return All trusted identities
124 * @throws PluginException
125 * if an error occured talking to the Web of Trust plugin
127 public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity) throws PluginException {
128 return loadTrustedIdentities(ownIdentity, null);
132 * Loads all identities that the given identities trusts with a score of
133 * more than 0 and the (optional) given context.
138 * The context to filter, or {@code null}
139 * @return All trusted identities
140 * @throws PluginException
141 * if an error occured talking to the Web of Trust plugin
143 public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity, Optional<String> context) throws PluginException {
144 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentitiesByScore").put("Truster", ownIdentity.getId()).put("Selection", "+").put("Context", context.or("")).put("WantTrustValues", "true").get());
145 SimpleFieldSet fields = reply.getFields();
146 Set<Identity> identities = new HashSet<Identity>();
147 int identityCounter = -1;
149 String id = fields.get("Identity" + ++identityCounter);
153 String nickname = fields.get("Nickname" + identityCounter);
154 String requestUri = fields.get("RequestURI" + identityCounter);
155 DefaultIdentity identity = new DefaultIdentity(id, nickname, requestUri);
156 identity.setContexts(parseContexts("Contexts" + identityCounter + ".", fields));
157 identity.setProperties(parseProperties("Properties" + identityCounter + ".", fields));
158 Integer trust = Numbers.safeParseInteger(fields.get("Trust" + identityCounter), null);
159 int score = Numbers.safeParseInteger(fields.get("Score" + identityCounter), 0);
160 int rank = Numbers.safeParseInteger(fields.get("Rank" + identityCounter), 0);
161 identity.setTrust(ownIdentity, new Trust(trust, score, rank));
162 identities.add(identity);
168 * Adds the given context to the given identity.
171 * The identity to add the context to
174 * @throws PluginException
175 * if an error occured talking to the Web of Trust plugin
177 public void addContext(OwnIdentity ownIdentity, String context) throws PluginException {
178 performRequest(SimpleFieldSetConstructor.create().put("Message", "AddContext").put("Identity", ownIdentity.getId()).put("Context", context).get());
182 * Removes the given context from the given identity.
185 * The identity to remove the context from
187 * The context to remove
188 * @throws PluginException
189 * if an error occured talking to the Web of Trust plugin
191 public void removeContext(OwnIdentity ownIdentity, String context) throws PluginException {
192 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveContext").put("Identity", ownIdentity.getId()).put("Context", context).get());
196 * Returns the value of the property with the given name.
199 * The identity whose properties to check
201 * The name of the property to return
202 * @return The value of the property, or {@code null} if there is no value
203 * @throws PluginException
204 * if an error occured talking to the Web of Trust plugin
206 public String getProperty(Identity identity, String name) throws PluginException {
207 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetProperty").put("Identity", identity.getId()).put("Property", name).get());
208 return reply.getFields().get("Property");
212 * Sets the property with the given name to the given value.
215 * The identity to set the property on
217 * The name of the property to set
220 * @throws PluginException
221 * if an error occured talking to the Web of Trust plugin
223 public void setProperty(OwnIdentity ownIdentity, String name, String value) throws PluginException {
224 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetProperty").put("Identity", ownIdentity.getId()).put("Property", name).put("Value", value).get());
228 * Removes the property with the given name.
231 * The identity to remove the property from
233 * The name of the property to remove
234 * @throws PluginException
235 * if an error occured talking to the Web of Trust plugin
237 public void removeProperty(OwnIdentity ownIdentity, String name) throws PluginException {
238 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveProperty").put("Identity", ownIdentity.getId()).put("Property", name).get());
242 * Returns the trust for the given identity assigned to it by the given own
248 * The identity to get the trust for
249 * @return The trust for the given identity
250 * @throws PluginException
251 * if an error occured talking to the Web of Trust plugin
253 public Trust getTrust(OwnIdentity ownIdentity, Identity identity) throws PluginException {
254 Reply getTrustReply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentity").put("Truster", ownIdentity.getId()).put("Identity", identity.getId()).get());
255 String trust = getTrustReply.getFields().get("Trust");
256 String score = getTrustReply.getFields().get("Score");
257 String rank = getTrustReply.getFields().get("Rank");
258 Integer explicit = null;
259 Integer implicit = null;
260 Integer distance = null;
262 explicit = Integer.valueOf(trust);
263 } catch (NumberFormatException nfe1) {
267 implicit = Integer.valueOf(score);
268 distance = Integer.valueOf(rank);
269 } catch (NumberFormatException nfe1) {
272 return new Trust(explicit, implicit, distance);
276 * Sets the trust for the given identity.
279 * The trusting identity
281 * The trusted identity
283 * The amount of trust (-100 thru 100)
285 * The comment or explanation of the trust value
286 * @throws PluginException
287 * if an error occured talking to the Web of Trust plugin
289 public void setTrust(OwnIdentity ownIdentity, Identity identity, int trust, String comment) throws PluginException {
290 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).put("Value", String.valueOf(trust)).put("Comment", comment).get());
294 * Removes any trust assignment of the given own identity for the given
300 * The identity to remove all trust for
301 * @throws WebOfTrustException
304 public void removeTrust(OwnIdentity ownIdentity, Identity identity) throws WebOfTrustException {
305 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).get());
309 * Pings the Web of Trust plugin. If the plugin can not be reached, a
310 * {@link PluginException} is thrown.
312 * @throws PluginException
313 * if the plugin is not loaded
315 public void ping() throws PluginException {
316 performRequest(SimpleFieldSetConstructor.create().put("Message", "Ping").get());
324 * Parses the contexts from the given fields.
327 * The prefix to use to access the contexts
329 * The fields to parse the contexts from
330 * @return The parsed contexts
332 private static Set<String> parseContexts(String prefix, SimpleFieldSet fields) {
333 Set<String> contexts = new HashSet<String>();
334 int contextCounter = -1;
336 String context = fields.get(prefix + "Context" + ++contextCounter);
337 if (context == null) {
340 contexts.add(context);
346 * Parses the properties from the given fields.
349 * The prefix to use to access the properties
351 * The fields to parse the properties from
352 * @return The parsed properties
354 private static Map<String, String> parseProperties(String prefix, SimpleFieldSet fields) {
355 Map<String, String> properties = new HashMap<String, String>();
356 int propertiesCounter = -1;
358 String propertyName = fields.get(prefix + "Property" + ++propertiesCounter + ".Name");
359 if (propertyName == null) {
362 String propertyValue = fields.get(prefix + "Property" + propertiesCounter + ".Value");
363 properties.put(propertyName, propertyValue);
369 * Sends a request containing the given fields and waits for the target
373 * The fields of the message
374 * @return The reply message
375 * @throws PluginException
376 * if the request could not be sent
378 private Reply performRequest(SimpleFieldSet fields) throws PluginException {
379 return performRequest(fields, null);
383 * Sends a request containing the given fields and waits for the target
387 * The fields of the message
389 * The payload of the message
390 * @return The reply message
391 * @throws PluginException
392 * if the request could not be sent
394 private Reply performRequest(SimpleFieldSet fields, Bucket data) throws PluginException {
395 String identifier = "FCP-Command-" + System.currentTimeMillis() + "-" + counter.getAndIncrement();
396 Reply reply = new Reply();
397 PluginIdentifier pluginIdentifier = new PluginIdentifier(WOT_PLUGIN_NAME, identifier);
398 replies.put(pluginIdentifier, reply);
400 logger.log(Level.FINE, String.format("Sending FCP Request: %s", fields.get("Message")));
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 replies.remove(pluginIdentifier);
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 * Notifies the connector that a plugin reply was received.
425 * @param receivedReplyEvent
429 public void receivedReply(ReceivedReplyEvent receivedReplyEvent) {
430 PluginIdentifier pluginIdentifier = new PluginIdentifier(receivedReplyEvent.pluginName(), receivedReplyEvent.identifier());
431 Reply reply = replies.remove(pluginIdentifier);
435 logger.log(Level.FINEST, String.format("Received Reply from Plugin: %s", receivedReplyEvent.fieldSet().get("Message")));
436 synchronized (reply) {
437 reply.setFields(receivedReplyEvent.fieldSet());
438 reply.setData(receivedReplyEvent.data());
444 * Container for the data of the reply from a plugin.
446 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
448 private static class Reply {
450 /** The fields of the reply. */
451 private SimpleFieldSet fields;
453 /** The payload of the reply. */
456 /** Empty constructor. */
462 * Returns the fields of the reply.
464 * @return The fields of the reply
466 public SimpleFieldSet getFields() {
471 * Sets the fields of the reply.
474 * The fields of the reply
476 public void setFields(SimpleFieldSet fields) {
477 this.fields = fields;
481 * Returns the payload of the reply.
483 * @return The payload of the reply (may be {@code null})
485 @SuppressWarnings("unused")
486 public Bucket getData() {
491 * Sets the payload of the reply.
494 * The payload of the reply (may be {@code null})
496 public void setData(Bucket data) {
503 * Helper method to create {@link SimpleFieldSet}s with terser code.
505 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
507 private static class SimpleFieldSetConstructor {
509 /** The field set being created. */
510 private SimpleFieldSet simpleFieldSet;
513 * Creates a new simple field set constructor.
516 * {@code true} if the resulting simple field set should be
517 * short-lived, {@code false} otherwise
519 private SimpleFieldSetConstructor(boolean shortLived) {
520 simpleFieldSet = new SimpleFieldSet(shortLived);
528 * Returns the created simple field set.
530 * @return The created simple field set
532 public SimpleFieldSet get() {
533 return simpleFieldSet;
537 * Sets the field with the given name to the given value.
540 * The name of the fleld
542 * The value of the field
543 * @return This constructor (for method chaining)
545 public SimpleFieldSetConstructor put(String name, String value) {
546 simpleFieldSet.putOverwrite(name, value);
555 * Creates a new simple field set constructor.
557 * @return The created simple field set constructor
559 public static SimpleFieldSetConstructor create() {
564 * Creates a new simple field set constructor.
567 * {@code true} if the resulting simple field set should be
568 * short-lived, {@code false} otherwise
569 * @return The created simple field set constructor
571 public static SimpleFieldSetConstructor create(boolean shortLived) {
572 return new SimpleFieldSetConstructor(shortLived);
578 * Container for identifying plugins. Plugins are identified by their plugin
579 * name and their unique identifier.
581 * @author <a href="mailto:d.roden@xplosion.de">David Roden</a>
583 private static class PluginIdentifier {
585 /** The plugin name. */
586 private final String pluginName;
588 /** The plugin identifier. */
589 private final String identifier;
592 * Creates a new plugin identifier.
595 * The name of the plugin
597 * The identifier of the plugin
599 public PluginIdentifier(String pluginName, String identifier) {
600 this.pluginName = pluginName;
601 this.identifier = identifier;
612 public int hashCode() {
613 return pluginName.hashCode() ^ identifier.hashCode();
620 public boolean equals(Object object) {
621 if (!(object instanceof PluginIdentifier)) {
624 PluginIdentifier pluginIdentifier = (PluginIdentifier) object;
625 return pluginName.equals(pluginIdentifier.pluginName) && identifier.equals(pluginIdentifier.identifier);