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;
34 import com.google.inject.Inject;
36 import freenet.support.SimpleFieldSet;
37 import freenet.support.api.Bucket;
40 * Connector for the Web of Trust plugin.
42 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
44 public class WebOfTrustConnector {
47 private static final Logger logger = Logging.getLogger(WebOfTrustConnector.class);
49 /** The name of the WoT plugin. */
50 private static final String WOT_PLUGIN_NAME = "plugins.WebOfTrust.WebOfTrust";
52 /** Counter for connection identifiers. */
53 private final AtomicLong counter = new AtomicLong();
55 /** The plugin connector. */
56 private final PluginConnector pluginConnector;
59 * Creates a new Web of Trust connector that uses the given plugin
62 * @param pluginConnector
63 * The plugin connector
66 public WebOfTrustConnector(PluginConnector pluginConnector) {
67 this.pluginConnector = pluginConnector;
75 * Stops the web of trust connector.
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 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetOwnIdentities").get());
90 SimpleFieldSet fields = reply.getFields();
91 int ownIdentityCounter = -1;
92 Set<OwnIdentity> ownIdentities = new HashSet<OwnIdentity>();
94 String id = fields.get("Identity" + ++ownIdentityCounter);
98 String requestUri = fields.get("RequestURI" + ownIdentityCounter);
99 String insertUri = fields.get("InsertURI" + ownIdentityCounter);
100 String nickname = fields.get("Nickname" + ownIdentityCounter);
101 DefaultOwnIdentity ownIdentity = new DefaultOwnIdentity(id, nickname, requestUri, insertUri);
102 ownIdentity.setContexts(parseContexts("Contexts" + ownIdentityCounter + ".", fields));
103 ownIdentity.setProperties(parseProperties("Properties" + ownIdentityCounter + ".", fields));
104 ownIdentities.add(ownIdentity);
106 return ownIdentities;
110 * Loads all identities that the given identities trusts with a score of
115 * @return All trusted identities
116 * @throws PluginException
117 * if an error occured talking to the Web of Trust plugin
119 public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity) throws PluginException {
120 return loadTrustedIdentities(ownIdentity, null);
124 * Loads all identities that the given identities trusts with a score of
125 * more than 0 and the (optional) given context.
130 * The context to filter, or {@code null}
131 * @return All trusted identities
132 * @throws PluginException
133 * if an error occured talking to the Web of Trust plugin
135 public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity, String context) throws PluginException {
136 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentitiesByScore").put("Truster", ownIdentity.getId()).put("Selection", "+").put("Context", (context == null) ? "" : context).put("WantTrustValues", "true").get());
137 SimpleFieldSet fields = reply.getFields();
138 Set<Identity> identities = new HashSet<Identity>();
139 int identityCounter = -1;
141 String id = fields.get("Identity" + ++identityCounter);
145 String nickname = fields.get("Nickname" + identityCounter);
146 String requestUri = fields.get("RequestURI" + identityCounter);
147 DefaultIdentity identity = new DefaultIdentity(id, nickname, requestUri);
148 identity.setContexts(parseContexts("Contexts" + identityCounter + ".", fields));
149 identity.setProperties(parseProperties("Properties" + identityCounter + ".", fields));
150 Integer trust = Numbers.safeParseInteger(fields.get("Trust" + identityCounter), null);
151 int score = Numbers.safeParseInteger(fields.get("Score" + identityCounter), 0);
152 int rank = Numbers.safeParseInteger(fields.get("Rank" + identityCounter), 0);
153 identity.setTrust(ownIdentity, new Trust(trust, score, rank));
154 identities.add(identity);
160 * Adds the given context to the given identity.
163 * The identity to add the context to
166 * @throws PluginException
167 * if an error occured talking to the Web of Trust plugin
169 public void addContext(OwnIdentity ownIdentity, String context) throws PluginException {
170 performRequest(SimpleFieldSetConstructor.create().put("Message", "AddContext").put("Identity", ownIdentity.getId()).put("Context", context).get());
174 * Removes the given context from the given identity.
177 * The identity to remove the context from
179 * The context to remove
180 * @throws PluginException
181 * if an error occured talking to the Web of Trust plugin
183 public void removeContext(OwnIdentity ownIdentity, String context) throws PluginException {
184 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveContext").put("Identity", ownIdentity.getId()).put("Context", context).get());
188 * Returns the value of the property with the given name.
191 * The identity whose properties to check
193 * The name of the property to return
194 * @return The value of the property, or {@code null} if there is no value
195 * @throws PluginException
196 * if an error occured talking to the Web of Trust plugin
198 public String getProperty(Identity identity, String name) throws PluginException {
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 static 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 static 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 Reply performRequest(SimpleFieldSet fields, Bucket data) throws PluginException {
387 final String identifier = "FCP-Command-" + System.currentTimeMillis() + "-" + counter.getAndIncrement();
388 final Reply reply = new Reply();
389 logger.log(Level.FINE, String.format("Sending FCP Request: %s", fields.get("Message")));
390 ConnectorListener connectorListener = new ConnectorListener() {
393 @SuppressWarnings("synthetic-access")
394 public void receivedReply(PluginConnector pluginConnector, SimpleFieldSet fields, Bucket data) {
395 String messageName = fields.get("Message");
396 logger.log(Level.FINEST, String.format("Received Reply from Plugin: %s", messageName));
397 synchronized (reply) {
398 reply.setFields(fields);
404 pluginConnector.addConnectorListener(WOT_PLUGIN_NAME, identifier, connectorListener);
405 synchronized (reply) {
407 pluginConnector.sendRequest(WOT_PLUGIN_NAME, identifier, fields, data);
408 while (reply.getFields() == null) {
411 } catch (InterruptedException ie1) {
412 logger.log(Level.WARNING, String.format("Got interrupted while waiting for reply on %s.", fields.get("Message")), ie1);
416 pluginConnector.removeConnectorListener(WOT_PLUGIN_NAME, identifier, connectorListener);
419 logger.log(Level.FINEST, String.format("Received FCP Response for %s: %s", fields.get("Message"), (reply.getFields() != null) ? reply.getFields().get("Message") : null));
420 if ((reply.getFields() == null) || "Error".equals(reply.getFields().get("Message"))) {
421 throw new PluginException("Could not perform request for " + fields.get("Message"));
427 * Container for the data of the reply from a plugin.
429 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
431 private static class Reply {
433 /** The fields of the reply. */
434 private SimpleFieldSet fields;
436 /** The payload of the reply. */
439 /** Empty constructor. */
445 * Returns the fields of the reply.
447 * @return The fields of the reply
449 public SimpleFieldSet getFields() {
454 * Sets the fields of the reply.
457 * The fields of the reply
459 public void setFields(SimpleFieldSet fields) {
460 this.fields = fields;
464 * Returns the payload of the reply.
466 * @return The payload of the reply (may be {@code null})
468 @SuppressWarnings("unused")
469 public Bucket getData() {
474 * Sets the payload of the reply.
477 * The payload of the reply (may be {@code null})
479 public void setData(Bucket data) {
486 * Helper method to create {@link SimpleFieldSet}s with terser code.
488 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
490 private static class SimpleFieldSetConstructor {
492 /** The field set being created. */
493 private SimpleFieldSet simpleFieldSet;
496 * Creates a new simple field set constructor.
499 * {@code true} if the resulting simple field set should be
500 * short-lived, {@code false} otherwise
502 private SimpleFieldSetConstructor(boolean shortLived) {
503 simpleFieldSet = new SimpleFieldSet(shortLived);
511 * Returns the created simple field set.
513 * @return The created simple field set
515 public SimpleFieldSet get() {
516 return simpleFieldSet;
520 * Sets the field with the given name to the given value.
523 * The name of the fleld
525 * The value of the field
526 * @return This constructor (for method chaining)
528 public SimpleFieldSetConstructor put(String name, String value) {
529 simpleFieldSet.putOverwrite(name, value);
538 * Creates a new simple field set constructor.
540 * @return The created simple field set constructor
542 public static SimpleFieldSetConstructor create() {
547 * Creates a new simple field set constructor.
550 * {@code true} if the resulting simple field set should be
551 * short-lived, {@code false} otherwise
552 * @return The created simple field set constructor
554 public static SimpleFieldSetConstructor create(boolean shortLived) {
555 SimpleFieldSetConstructor simpleFieldSetConstructor = new SimpleFieldSetConstructor(shortLived);
556 return simpleFieldSetConstructor;