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.wotns.freenet.wot;
20 import java.util.HashMap;
21 import java.util.HashSet;
24 import java.util.logging.Level;
25 import java.util.logging.Logger;
27 import net.pterodactylus.util.logging.Logging;
28 import net.pterodactylus.util.number.Numbers;
29 import net.pterodactylus.wotns.freenet.plugin.ConnectorListener;
30 import net.pterodactylus.wotns.freenet.plugin.PluginConnector;
31 import net.pterodactylus.wotns.freenet.plugin.PluginException;
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.WebOfTrust.WebOfTrust";
48 /** A random connection identifier. */
49 private static final String PLUGIN_CONNECTION_IDENTIFIER = "WoTNS-WoT-Connector-" + Math.abs(Math.random());
51 /** The current 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 pluginConnector.removeConnectorListener(WOT_PLUGIN_NAME, PLUGIN_CONNECTION_IDENTIFIER, this);
78 * Loads all own identities from the Web of Trust plugin.
80 * @return All own identity
81 * @throws WebOfTrustException
82 * if the own identities can not be loaded
84 public Set<OwnIdentity> loadAllOwnIdentities() throws WebOfTrustException {
85 @SuppressWarnings("hiding")
86 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetOwnIdentities").get());
87 SimpleFieldSet fields = reply.getFields();
88 int ownIdentityCounter = -1;
89 Set<OwnIdentity> ownIdentities = new HashSet<OwnIdentity>();
91 String id = fields.get("Identity" + ++ownIdentityCounter);
95 String requestUri = fields.get("RequestURI" + ownIdentityCounter);
96 String insertUri = fields.get("InsertURI" + ownIdentityCounter);
97 String nickname = fields.get("Nickname" + ownIdentityCounter);
98 DefaultOwnIdentity ownIdentity = new DefaultOwnIdentity(this, id, nickname, requestUri, insertUri);
99 ownIdentity.setContextsPrivate(parseContexts("Contexts" + ownIdentityCounter + ".", fields));
100 ownIdentity.setPropertiesPrivate(parseProperties("Properties" + ownIdentityCounter + ".", fields));
101 ownIdentities.add(ownIdentity);
103 return ownIdentities;
107 * Loads all identities that the given identities trusts with a score of
112 * @return All trusted identities
113 * @throws PluginException
114 * if an error occured talking to the Web of Trust plugin
116 public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity) throws PluginException {
117 return loadTrustedIdentities(ownIdentity, null);
121 * Loads all identities that the given identities trusts with a score of
122 * more than 0 and the (optional) given context.
127 * The context to filter, or {@code null}
128 * @return All trusted identities
129 * @throws PluginException
130 * if an error occured talking to the Web of Trust plugin
132 public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity, String context) throws PluginException {
133 @SuppressWarnings("hiding")
134 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentitiesByScore").put("TreeOwner", ownIdentity.getId()).put("Selection", "+").put("Context", (context == null) ? "" : context).get());
135 SimpleFieldSet fields = reply.getFields();
136 Set<Identity> identities = new HashSet<Identity>();
137 int identityCounter = -1;
139 String id = fields.get("Identity" + ++identityCounter);
143 String nickname = fields.get("Nickname" + identityCounter);
144 String requestUri = fields.get("RequestURI" + identityCounter);
145 DefaultIdentity identity = new DefaultIdentity(this, id, nickname, requestUri);
146 identity.setContextsPrivate(parseContexts("Contexts" + identityCounter + ".", fields));
147 identity.setPropertiesPrivate(parseProperties("Properties" + identityCounter + ".", fields));
148 identity.setTrustPrivate(ownIdentity, new Trust(Numbers.safeParseInteger(fields.get("Trust" + identityCounter)), Numbers.safeParseInteger(fields.get("Score" + identityCounter)), Numbers.safeParseInteger(fields.get("Rank" + identityCounter))));
149 identities.add(identity);
155 * Adds the given context to the given identity.
158 * The identity to add the context to
161 * @throws PluginException
162 * if an error occured talking to the Web of Trust plugin
164 public void addContext(OwnIdentity ownIdentity, String context) throws PluginException {
165 performRequest(SimpleFieldSetConstructor.create().put("Message", "AddContext").put("Identity", ownIdentity.getId()).put("Context", context).get());
169 * Removes the given context from the given identity.
172 * The identity to remove the context from
174 * The context to remove
175 * @throws PluginException
176 * if an error occured talking to the Web of Trust plugin
178 public void removeContext(OwnIdentity ownIdentity, String context) throws PluginException {
179 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveContext").put("Identity", ownIdentity.getId()).put("Context", context).get());
183 * Returns the value of the property with the given name.
186 * The identity whose properties to check
188 * The name of the property to return
189 * @return The value of the property, or {@code null} if there is no value
190 * @throws PluginException
191 * if an error occured talking to the Web of Trust plugin
193 public String getProperty(Identity identity, String name) throws PluginException {
194 @SuppressWarnings("hiding")
195 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetProperty").put("Identity", identity.getId()).put("Property", name).get());
196 return reply.getFields().get("Property");
200 * Sets the property with the given name to the given value.
203 * The identity to set the property on
205 * The name of the property to set
208 * @throws PluginException
209 * if an error occured talking to the Web of Trust plugin
211 public void setProperty(OwnIdentity ownIdentity, String name, String value) throws PluginException {
212 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetProperty").put("Identity", ownIdentity.getId()).put("Property", name).put("Value", value).get());
216 * Removes the property with the given name.
219 * The identity to remove the property from
221 * The name of the property to remove
222 * @throws PluginException
223 * if an error occured talking to the Web of Trust plugin
225 public void removeProperty(OwnIdentity ownIdentity, String name) throws PluginException {
226 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveProperty").put("Identity", ownIdentity.getId()).put("Property", name).get());
230 * Returns the trust for the given identity assigned to it by the given own
236 * The identity to get the trust for
237 * @return The trust for the given identity
238 * @throws PluginException
239 * if an error occured talking to the Web of Trust plugin
241 public Trust getTrust(OwnIdentity ownIdentity, Identity identity) throws PluginException {
242 Reply getTrustReply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentity").put("Truster", ownIdentity.getId()).put("Identity", identity.getId()).get());
243 String trust = getTrustReply.getFields().get("Trust");
244 String score = getTrustReply.getFields().get("Score");
245 String rank = getTrustReply.getFields().get("Rank");
246 Integer explicit = null;
247 Integer implicit = null;
248 Integer distance = null;
250 explicit = Integer.valueOf(trust);
251 } catch (NumberFormatException nfe1) {
255 implicit = Integer.valueOf(score);
256 distance = Integer.valueOf(rank);
257 } catch (NumberFormatException nfe1) {
260 return new Trust(explicit, implicit, distance);
264 * Sets the trust for the given identity.
267 * The trusting identity
269 * The trusted identity
271 * The amount of trust (-100 thru 100)
273 * The comment or explanation of the trust value
274 * @throws PluginException
275 * if an error occured talking to the Web of Trust plugin
277 public void setTrust(OwnIdentity ownIdentity, Identity identity, int trust, String comment) throws PluginException {
278 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).put("Value", String.valueOf(trust)).put("Comment", comment).get());
282 * Removes any trust assignment of the given own identity for the given
288 * The identity to remove all trust for
289 * @throws WebOfTrustException
292 public void removeTrust(OwnIdentity ownIdentity, Identity identity) throws WebOfTrustException {
293 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).get());
297 * Pings the Web of Trust plugin. If the plugin can not be reached, a
298 * {@link PluginException} is thrown.
300 * @throws PluginException
301 * if the plugin is not loaded
303 public void ping() throws PluginException {
304 performRequest(SimpleFieldSetConstructor.create().put("Message", "Ping").get());
312 * Parses the contexts from the given fields.
315 * The prefix to use to access the contexts
317 * The fields to parse the contexts from
318 * @return The parsed contexts
320 private Set<String> parseContexts(String prefix, SimpleFieldSet fields) {
321 Set<String> contexts = new HashSet<String>();
322 int contextCounter = -1;
324 String context = fields.get(prefix + "Context" + ++contextCounter);
325 if (context == null) {
328 contexts.add(context);
334 * Parses the properties from the given fields.
337 * The prefix to use to access the properties
339 * The fields to parse the properties from
340 * @return The parsed properties
342 private Map<String, String> parseProperties(String prefix, SimpleFieldSet fields) {
343 Map<String, String> properties = new HashMap<String, String>();
344 int propertiesCounter = -1;
346 String propertyName = fields.get(prefix + "Property" + ++propertiesCounter + ".Name");
347 if (propertyName == null) {
350 String propertyValue = fields.get(prefix + "Property" + propertiesCounter + ".Value");
351 properties.put(propertyName, propertyValue);
357 * Sends a request containing the given fields and waits for the target
361 * The fields of the message
362 * @return The reply message
363 * @throws PluginException
364 * if the request could not be sent
366 private Reply performRequest(SimpleFieldSet fields) throws PluginException {
367 return performRequest(fields, null);
371 * Sends a request containing the given fields and waits for the target
375 * The fields of the message
377 * The payload of the message
378 * @return The reply message
379 * @throws PluginException
380 * if the request could not be sent
382 private synchronized Reply performRequest(SimpleFieldSet fields, Bucket data) throws PluginException {
384 logger.log(Level.FINE, "Sending FCP Request: " + fields.get("Message"));
385 synchronized (reply) {
386 pluginConnector.sendRequest(WOT_PLUGIN_NAME, PLUGIN_CONNECTION_IDENTIFIER, fields, data);
389 } catch (InterruptedException ie1) {
390 logger.log(Level.WARNING, "Got interrupted while waiting for reply on " + fields.get("Message") + ".", ie1);
393 logger.log(Level.FINEST, "Received FCP Response for %s: %s", new Object[] { fields.get("Message"), (reply.getFields() != null) ? reply.getFields().get("Message") : null });
394 if ((reply.getFields() == null) || "Error".equals(reply.getFields().get("Message"))) {
395 throw new PluginException("Could not perform request for " + fields.get("Message"));
401 // INTERFACE ConnectorListener
408 public void receivedReply(@SuppressWarnings("hiding") PluginConnector pluginConnector, SimpleFieldSet fields, Bucket data) {
409 String messageName = fields.get("Message");
410 logger.log(Level.FINEST, "Received Reply from Plugin: " + messageName);
411 synchronized (reply) {
412 reply.setFields(fields);
419 * Container for the data of the reply from a plugin.
421 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
423 private static class Reply {
425 /** The fields of the reply. */
426 private SimpleFieldSet fields;
428 /** The payload of the reply. */
431 /** Empty constructor. */
437 * Returns the fields of the reply.
439 * @return The fields of the reply
441 public SimpleFieldSet getFields() {
446 * Sets the fields of the reply.
449 * The fields of the reply
451 public void setFields(SimpleFieldSet fields) {
452 this.fields = fields;
456 * Returns the payload of the reply.
458 * @return The payload of the reply (may be {@code null})
460 @SuppressWarnings("unused")
461 public Bucket getData() {
466 * Sets the payload of the reply.
469 * The payload of the reply (may be {@code null})
471 public void setData(Bucket data) {
478 * Helper method to create {@link SimpleFieldSet}s with terser code.
480 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
482 private static class SimpleFieldSetConstructor {
484 /** The field set being created. */
485 private SimpleFieldSet simpleFieldSet;
488 * Creates a new simple field set constructor.
491 * {@code true} if the resulting simple field set should be
492 * short-lived, {@code false} otherwise
494 private SimpleFieldSetConstructor(boolean shortLived) {
495 simpleFieldSet = new SimpleFieldSet(shortLived);
503 * Returns the created simple field set.
505 * @return The created simple field set
507 public SimpleFieldSet get() {
508 return simpleFieldSet;
512 * Sets the field with the given name to the given value.
515 * The name of the fleld
517 * The value of the field
518 * @return This constructor (for method chaining)
520 public SimpleFieldSetConstructor put(String name, String value) {
521 simpleFieldSet.putOverwrite(name, value);
530 * Creates a new simple field set constructor.
532 * @return The created simple field set constructor
534 public static SimpleFieldSetConstructor create() {
539 * Creates a new simple field set constructor.
542 * {@code true} if the resulting simple field set should be
543 * short-lived, {@code false} otherwise
544 * @return The created simple field set constructor
546 public static SimpleFieldSetConstructor create(boolean shortLived) {
547 SimpleFieldSetConstructor simpleFieldSetConstructor = new SimpleFieldSetConstructor(shortLived);
548 return simpleFieldSetConstructor;