2 * Sone - WebOfTrustConnector.java - Copyright © 2010 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.Collections;
21 import java.util.HashMap;
22 import java.util.HashSet;
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 freenet.support.SimpleFieldSet;
33 import freenet.support.api.Bucket;
36 * Connector for the Web of Trust plugin.
38 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
40 public class WebOfTrustConnector implements ConnectorListener {
43 private static final Logger logger = Logging.getLogger(WebOfTrustConnector.class);
45 /** The name of the WoT plugin. */
46 private static final String WOT_PLUGIN_NAME = "plugins.WoT.WoT";
48 /** A random connection identifier. */
49 private static final String PLUGIN_CONNECTION_IDENTIFIER = "Sone-WoT-Connector-" + Math.abs(Math.random());
51 /** The current replies that we wait for. */
52 private final Map<String, Reply> replies = Collections.synchronizedMap(new HashMap<String, Reply>());
54 /** The plugin connector. */
55 private final PluginConnector pluginConnector;
58 * Creates a new Web of Trust connector that uses the given plugin
61 * @param pluginConnector
62 * The plugin connector
64 public WebOfTrustConnector(PluginConnector pluginConnector) {
65 this.pluginConnector = pluginConnector;
66 pluginConnector.addConnectorListener(WOT_PLUGIN_NAME, PLUGIN_CONNECTION_IDENTIFIER, this);
74 * Loads all own identities from the Web of Trust plugin.
76 * @return All own identity
77 * @throws WebOfTrustException
78 * if the own identities can not be loaded
80 public Set<OwnIdentity> loadAllOwnIdentities() throws WebOfTrustException {
81 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetOwnIdentities").get(), "OwnIdentities");
82 SimpleFieldSet fields = reply.getFields();
83 int ownIdentityCounter = -1;
84 Set<OwnIdentity> ownIdentities = new HashSet<OwnIdentity>();
86 String id = fields.get("Identity" + ++ownIdentityCounter);
90 String requestUri = fields.get("RequestURI" + ownIdentityCounter);
91 String insertUri = fields.get("InsertURI" + ownIdentityCounter);
92 String nickname = fields.get("Nickname" + ownIdentityCounter);
93 DefaultOwnIdentity ownIdentity = new DefaultOwnIdentity(this, id, nickname, requestUri, insertUri);
94 ownIdentity.setContextsPrivate(parseContexts("Contexts" + ownIdentityCounter + ".", fields));
95 ownIdentity.setPropertiesPrivate(parseProperties("Properties" + ownIdentityCounter + ".", fields));
96 ownIdentities.add(ownIdentity);
102 * Loads all identities that the given identities trusts with a score of
107 * @return All trusted identities
108 * @throws PluginException
109 * if an error occured talking to the Web of Trust plugin
111 public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity) throws PluginException {
112 return loadTrustedIdentities(ownIdentity, null);
116 * Loads all identities that the given identities trusts with a score of
117 * more than 0 and the (optional) given context.
122 * The context to filter, or {@code null}
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, String context) throws PluginException {
128 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentitiesByScore").put("TreeOwner", ownIdentity.getId()).put("Selection", "+").put("Context", (context == null) ? "" : context).get(), "Identities");
129 SimpleFieldSet fields = reply.getFields();
130 Set<Identity> identities = new HashSet<Identity>();
131 int identityCounter = -1;
133 String id = fields.get("Identity" + ++identityCounter);
137 String nickname = fields.get("Nickname" + identityCounter);
138 String requestUri = fields.get("RequestURI" + identityCounter);
139 DefaultIdentity identity = new DefaultIdentity(this, id, nickname, requestUri);
140 identity.setContextsPrivate(parseContexts("Contexts" + identityCounter + ".", fields));
141 identity.setPropertiesPrivate(parseProperties("Properties" + identityCounter + ".", fields));
142 identities.add(identity);
148 * Adds the given context to the given identity.
151 * The identity to add the context to
154 * @throws PluginException
155 * if an error occured talking to the Web of Trust plugin
157 public void addContext(OwnIdentity ownIdentity, String context) throws PluginException {
158 performRequest(SimpleFieldSetConstructor.create().put("Message", "AddContext").put("Identity", ownIdentity.getId()).put("Context", context).get(), "ContextAdded");
162 * Removes the given context from the given identity.
165 * The identity to remove the context from
167 * The context to remove
168 * @throws PluginException
169 * if an error occured talking to the Web of Trust plugin
171 public void removeContext(OwnIdentity ownIdentity, String context) throws PluginException {
172 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveContext").put("Identity", ownIdentity.getId()).put("Context", context).get(), "ContextRemoved");
176 * Returns the value of the property with the given name.
179 * The identity whose properties to check
181 * The name of the property to return
182 * @return The value of the property, or {@code null} if there is no value
183 * @throws PluginException
184 * if an error occured talking to the Web of Trust plugin
186 public String getProperty(Identity identity, String name) throws PluginException {
187 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetProperty").put("Identity", identity.getId()).put("Property", name).get(), "PropertyValue");
188 return reply.getFields().get("Property");
192 * Sets the property with the given name to the given value.
195 * The identity to set the property on
197 * The name of the property to set
200 * @throws PluginException
201 * if an error occured talking to the Web of Trust plugin
203 public void setProperty(OwnIdentity ownIdentity, String name, String value) throws PluginException {
204 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetProperty").put("Identity", ownIdentity.getId()).put("Property", name).put("Value", value).get(), "PropertyAdded");
208 * Removes the property with the given name.
211 * The identity to remove the property from
213 * The name of the property to remove
214 * @throws PluginException
215 * if an error occured talking to the Web of Trust plugin
217 public void removeProperty(OwnIdentity ownIdentity, String name) throws PluginException {
218 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveProperty").put("Identity", ownIdentity.getId()).put("Property", name).get(), "PropertyRemoved");
222 * Returns the trust for the given identity assigned to it by the given own
228 * The identity to get the trust for
229 * @return The trust for the given identity
230 * @throws PluginException
231 * if an error occured talking to the Web of Trust plugin
233 public Trust getTrust(OwnIdentity ownIdentity, Identity identity) throws PluginException {
234 Reply getTrustReply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentity").put("TreeOwner", ownIdentity.getId()).put("Identity", identity.getId()).get(), "Identity");
235 String trust = getTrustReply.getFields().get("Trust");
236 String score = getTrustReply.getFields().get("Score");
237 String rank = getTrustReply.getFields().get("Rank");
238 Integer explicit = null;
239 Integer implicit = null;
240 Integer distance = null;
242 explicit = Integer.valueOf(trust);
243 } catch (NumberFormatException nfe1) {
247 implicit = Integer.valueOf(score);
248 distance = Integer.valueOf(rank);
249 } catch (NumberFormatException nfe1) {
252 return new Trust(explicit, implicit, distance);
256 * Sets the trust for the given identity.
259 * The trusting identity
261 * The trusted identity
263 * The amount of trust (-100 thru 100)
265 * The comment or explanation of the trust value
266 * @throws PluginException
267 * if an error occured talking to the Web of Trust plugin
269 public void setTrust(OwnIdentity ownIdentity, Identity identity, int trust, String comment) throws PluginException {
270 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).put("Value", String.valueOf(trust)).put("Comment", comment).get(), "TrustSet");
274 * Removes any trust assignment of the given own identity for the given
280 * The identity to remove all trust for
281 * @throws WebOfTrustException
284 public void removeTrust(OwnIdentity ownIdentity, Identity identity) throws WebOfTrustException {
285 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).get(), "TrustRemoved");
289 * Pings the Web of Trust plugin. If the plugin can not be reached, a
290 * {@link PluginException} is thrown.
292 * @throws PluginException
293 * if the plugin is not loaded
295 public void ping() throws PluginException {
296 performRequest(SimpleFieldSetConstructor.create().put("Message", "Ping").get(), "Pong");
304 * Parses the contexts from the given fields.
307 * The prefix to use to access the contexts
309 * The fields to parse the contexts from
310 * @return The parsed contexts
312 private Set<String> parseContexts(String prefix, SimpleFieldSet fields) {
313 Set<String> contexts = new HashSet<String>();
314 int contextCounter = -1;
316 String context = fields.get(prefix + "Context" + ++contextCounter);
317 if (context == null) {
320 contexts.add(context);
326 * Parses the properties from the given fields.
329 * The prefix to use to access the properties
331 * The fields to parse the properties from
332 * @return The parsed properties
334 private Map<String, String> parseProperties(String prefix, SimpleFieldSet fields) {
335 Map<String, String> properties = new HashMap<String, String>();
336 int propertiesCounter = -1;
338 String propertyName = fields.get(prefix + "Property" + ++propertiesCounter + ".Name");
339 if (propertyName == null) {
342 String propertyValue = fields.get(prefix + "Property" + propertiesCounter + ".Value");
343 properties.put(propertyName, propertyValue);
349 * Sends a request containing the given fields and waits for the target
353 * The fields of the message
354 * @param targetMessages
355 * The messages of the reply to wait for
356 * @return The reply message
357 * @throws PluginException
358 * if the request could not be sent
360 private Reply performRequest(SimpleFieldSet fields, String... targetMessages) throws PluginException {
361 return performRequest(fields, null, targetMessages);
365 * Sends a request containing the given fields and waits for the target
369 * The fields of the message
371 * The payload of the message
372 * @param targetMessages
373 * The messages of the reply to wait for
374 * @return The reply message
375 * @throws PluginException
376 * if the request could not be sent
378 private Reply performRequest(SimpleFieldSet fields, Bucket data, String... targetMessages) throws PluginException {
379 @SuppressWarnings("synthetic-access")
380 Reply reply = new Reply();
381 for (String targetMessage : targetMessages) {
382 replies.put(targetMessage, reply);
384 replies.put("Error", reply);
385 synchronized (reply) {
386 pluginConnector.sendRequest(WOT_PLUGIN_NAME, PLUGIN_CONNECTION_IDENTIFIER, fields, data);
388 long now = System.currentTimeMillis();
389 while ((reply.getFields() == null) && ((System.currentTimeMillis() - now) < 60000)) {
390 reply.wait(60000 - (System.currentTimeMillis() - now));
392 if (reply.getFields() == null) {
393 for (String targetMessage : targetMessages) {
394 replies.remove(targetMessage);
396 replies.remove("Error");
397 throw new PluginException("Timeout waiting for " + targetMessages[0] + "!");
399 } catch (InterruptedException ie1) {
400 logger.log(Level.WARNING, "Got interrupted while waiting for reply on " + targetMessages[0] + ".", ie1);
403 for (String targetMessage : targetMessages) {
404 replies.remove(targetMessage);
406 replies.remove("Error");
407 if ((reply.getFields() != null) && reply.getFields().get("Message").equals("Error")) {
408 throw new PluginException("Could not perform request for " + targetMessages[0]);
414 // INTERFACE ConnectorListener
421 public void receivedReply(PluginConnector pluginConnector, SimpleFieldSet fields, Bucket data) {
422 String messageName = fields.get("Message");
423 logger.log(Level.FINEST, "Received Reply from Plugin: " + messageName);
424 Reply reply = replies.remove(messageName);
426 logger.log(Level.FINE, "Not waiting for a “%s” message.", messageName);
429 synchronized (reply) {
430 reply.setFields(fields);
437 * Container for the data of the reply from a plugin.
439 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
441 private static class Reply {
443 /** The fields of the reply. */
444 private SimpleFieldSet fields;
446 /** The payload of the reply. */
450 * Returns the fields of the reply.
452 * @return The fields of the reply
454 public SimpleFieldSet getFields() {
459 * Sets the fields of the reply.
462 * The fields of the reply
464 public void setFields(SimpleFieldSet fields) {
465 this.fields = fields;
469 * Returns the payload of the reply.
471 * @return The payload of the reply (may be {@code null})
473 @SuppressWarnings("unused")
474 public Bucket getData() {
479 * Sets the payload of the reply.
482 * The payload of the reply (may be {@code null})
484 public void setData(Bucket data) {
491 * Helper method to create {@link SimpleFieldSet}s with terser code.
493 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
495 private static class SimpleFieldSetConstructor {
497 /** The field set being created. */
498 private SimpleFieldSet simpleFieldSet;
501 * Creates a new simple field set constructor.
504 * {@code true} if the resulting simple field set should be
505 * short-lived, {@code false} otherwise
507 private SimpleFieldSetConstructor(boolean shortLived) {
508 simpleFieldSet = new SimpleFieldSet(shortLived);
516 * Returns the created simple field set.
518 * @return The created simple field set
520 public SimpleFieldSet get() {
521 return simpleFieldSet;
525 * Sets the field with the given name to the given value.
528 * The name of the fleld
530 * The value of the field
531 * @return This constructor (for method chaining)
533 public SimpleFieldSetConstructor put(String name, String value) {
534 simpleFieldSet.putOverwrite(name, value);
543 * Creates a new simple field set constructor.
545 * @return The created simple field set constructor
547 public static SimpleFieldSetConstructor create() {
552 * Creates a new simple field set constructor.
555 * {@code true} if the resulting simple field set should be
556 * short-lived, {@code false} otherwise
557 * @return The created simple field set constructor
559 public static SimpleFieldSetConstructor create(boolean shortLived) {
560 SimpleFieldSetConstructor simpleFieldSetConstructor = new SimpleFieldSetConstructor(shortLived);
561 return simpleFieldSetConstructor;