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.HashMap;
21 import java.util.HashSet;
24 import java.util.logging.Level;
25 import java.util.logging.Logger;
27 import net.pterodactylus.sone.freenet.plugin.ConnectorListener;
28 import net.pterodactylus.sone.freenet.plugin.PluginConnector;
29 import net.pterodactylus.sone.freenet.plugin.PluginException;
30 import net.pterodactylus.util.logging.Logging;
31 import freenet.support.SimpleFieldSet;
32 import freenet.support.api.Bucket;
35 * Connector for the Web of Trust plugin.
37 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
39 public class WebOfTrustConnector implements ConnectorListener {
42 private static final Logger logger = Logging.getLogger(WebOfTrustConnector.class);
44 /** The name of the WoT plugin. */
45 private static final String WOT_PLUGIN_NAME = "plugins.WebOfTrust.WebOfTrust";
47 /** A random connection identifier. */
48 private static final String PLUGIN_CONNECTION_IDENTIFIER = "Sone-WoT-Connector-" + Math.abs(Math.random());
50 /** The current reply. */
53 /** The plugin connector. */
54 private final PluginConnector pluginConnector;
57 * Creates a new Web of Trust connector that uses the given plugin
60 * @param pluginConnector
61 * The plugin connector
63 public WebOfTrustConnector(PluginConnector pluginConnector) {
64 this.pluginConnector = pluginConnector;
65 pluginConnector.addConnectorListener(WOT_PLUGIN_NAME, PLUGIN_CONNECTION_IDENTIFIER, this);
73 * Stops the web of trust connector.
76 pluginConnector.removeConnectorListener(WOT_PLUGIN_NAME, PLUGIN_CONNECTION_IDENTIFIER, this);
80 * Loads all own identities from the Web of Trust plugin.
82 * @return All own identity
83 * @throws WebOfTrustException
84 * if the own identities can not be loaded
86 public Set<OwnIdentity> loadAllOwnIdentities() throws WebOfTrustException {
87 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetOwnIdentities").get());
88 SimpleFieldSet fields = reply.getFields();
89 int ownIdentityCounter = -1;
90 Set<OwnIdentity> ownIdentities = new HashSet<OwnIdentity>();
92 String id = fields.get("Identity" + ++ownIdentityCounter);
96 String requestUri = fields.get("RequestURI" + ownIdentityCounter);
97 String insertUri = fields.get("InsertURI" + ownIdentityCounter);
98 String nickname = fields.get("Nickname" + ownIdentityCounter);
99 DefaultOwnIdentity ownIdentity = new DefaultOwnIdentity(this, id, nickname, requestUri, insertUri);
100 ownIdentity.setContextsPrivate(parseContexts("Contexts" + ownIdentityCounter + ".", fields));
101 ownIdentity.setPropertiesPrivate(parseProperties("Properties" + ownIdentityCounter + ".", fields));
102 ownIdentities.add(ownIdentity);
104 return ownIdentities;
108 * Loads all identities that the given identities trusts with a score of
113 * @return All trusted identities
114 * @throws PluginException
115 * if an error occured talking to the Web of Trust plugin
117 public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity) throws PluginException {
118 return loadTrustedIdentities(ownIdentity, null);
122 * Loads all identities that the given identities trusts with a score of
123 * more than 0 and the (optional) given context.
128 * The context to filter, or {@code null}
129 * @return All trusted identities
130 * @throws PluginException
131 * if an error occured talking to the Web of Trust plugin
133 public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity, String context) throws PluginException {
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 identities.add(identity);
154 * Adds the given context to the given identity.
157 * The identity to add the context to
160 * @throws PluginException
161 * if an error occured talking to the Web of Trust plugin
163 public void addContext(OwnIdentity ownIdentity, String context) throws PluginException {
164 performRequest(SimpleFieldSetConstructor.create().put("Message", "AddContext").put("Identity", ownIdentity.getId()).put("Context", context).get());
168 * Removes the given context from the given identity.
171 * The identity to remove the context from
173 * The context to remove
174 * @throws PluginException
175 * if an error occured talking to the Web of Trust plugin
177 public void removeContext(OwnIdentity ownIdentity, String context) throws PluginException {
178 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveContext").put("Identity", ownIdentity.getId()).put("Context", context).get());
182 * Returns the value of the property with the given name.
185 * The identity whose properties to check
187 * The name of the property to return
188 * @return The value of the property, or {@code null} if there is no value
189 * @throws PluginException
190 * if an error occured talking to the Web of Trust plugin
192 public String getProperty(Identity identity, String name) throws PluginException {
193 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetProperty").put("Identity", identity.getId()).put("Property", name).get());
194 return reply.getFields().get("Property");
198 * Sets the property with the given name to the given value.
201 * The identity to set the property on
203 * The name of the property to set
206 * @throws PluginException
207 * if an error occured talking to the Web of Trust plugin
209 public void setProperty(OwnIdentity ownIdentity, String name, String value) throws PluginException {
210 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetProperty").put("Identity", ownIdentity.getId()).put("Property", name).put("Value", value).get());
214 * Removes the property with the given name.
217 * The identity to remove the property from
219 * The name of the property to remove
220 * @throws PluginException
221 * if an error occured talking to the Web of Trust plugin
223 public void removeProperty(OwnIdentity ownIdentity, String name) throws PluginException {
224 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveProperty").put("Identity", ownIdentity.getId()).put("Property", name).get());
228 * Returns the trust for the given identity assigned to it by the given own
234 * The identity to get the trust for
235 * @return The trust for the given identity
236 * @throws PluginException
237 * if an error occured talking to the Web of Trust plugin
239 public Trust getTrust(OwnIdentity ownIdentity, Identity identity) throws PluginException {
240 Reply getTrustReply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentity").put("Truster", ownIdentity.getId()).put("Identity", identity.getId()).get());
241 String trust = getTrustReply.getFields().get("Trust");
242 String score = getTrustReply.getFields().get("Score");
243 String rank = getTrustReply.getFields().get("Rank");
244 Integer explicit = null;
245 Integer implicit = null;
246 Integer distance = null;
248 explicit = Integer.valueOf(trust);
249 } catch (NumberFormatException nfe1) {
253 implicit = Integer.valueOf(score);
254 distance = Integer.valueOf(rank);
255 } catch (NumberFormatException nfe1) {
258 return new Trust(explicit, implicit, distance);
262 * Sets the trust for the given identity.
265 * The trusting identity
267 * The trusted identity
269 * The amount of trust (-100 thru 100)
271 * The comment or explanation of the trust value
272 * @throws PluginException
273 * if an error occured talking to the Web of Trust plugin
275 public void setTrust(OwnIdentity ownIdentity, Identity identity, int trust, String comment) throws PluginException {
276 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).put("Value", String.valueOf(trust)).put("Comment", comment).get());
280 * Removes any trust assignment of the given own identity for the given
286 * The identity to remove all trust for
287 * @throws WebOfTrustException
290 public void removeTrust(OwnIdentity ownIdentity, Identity identity) throws WebOfTrustException {
291 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).get());
295 * Pings the Web of Trust plugin. If the plugin can not be reached, a
296 * {@link PluginException} is thrown.
298 * @throws PluginException
299 * if the plugin is not loaded
301 public void ping() throws PluginException {
302 performRequest(SimpleFieldSetConstructor.create().put("Message", "Ping").get());
310 * Parses the contexts from the given fields.
313 * The prefix to use to access the contexts
315 * The fields to parse the contexts from
316 * @return The parsed contexts
318 private Set<String> parseContexts(String prefix, SimpleFieldSet fields) {
319 Set<String> contexts = new HashSet<String>();
320 int contextCounter = -1;
322 String context = fields.get(prefix + "Context" + ++contextCounter);
323 if (context == null) {
326 contexts.add(context);
332 * Parses the properties from the given fields.
335 * The prefix to use to access the properties
337 * The fields to parse the properties from
338 * @return The parsed properties
340 private Map<String, String> parseProperties(String prefix, SimpleFieldSet fields) {
341 Map<String, String> properties = new HashMap<String, String>();
342 int propertiesCounter = -1;
344 String propertyName = fields.get(prefix + "Property" + ++propertiesCounter + ".Name");
345 if (propertyName == null) {
348 String propertyValue = fields.get(prefix + "Property" + propertiesCounter + ".Value");
349 properties.put(propertyName, propertyValue);
355 * Sends a request containing the given fields and waits for the target
359 * The fields of the message
360 * @return The reply message
361 * @throws PluginException
362 * if the request could not be sent
364 private Reply performRequest(SimpleFieldSet fields) throws PluginException {
365 return performRequest(fields, null);
369 * Sends a request containing the given fields and waits for the target
373 * The fields of the message
375 * The payload of the message
376 * @return The reply message
377 * @throws PluginException
378 * if the request could not be sent
380 private synchronized Reply performRequest(SimpleFieldSet fields, Bucket data) throws PluginException {
382 logger.log(Level.FINE, "Sending FCP Request: " + fields.get("Message"));
383 synchronized (reply) {
384 pluginConnector.sendRequest(WOT_PLUGIN_NAME, PLUGIN_CONNECTION_IDENTIFIER, fields, data);
387 } catch (InterruptedException ie1) {
388 logger.log(Level.WARNING, "Got interrupted while waiting for reply on " + fields.get("Message") + ".", ie1);
391 logger.log(Level.FINEST, "Received FCP Response for %s: %s", new Object[] { fields.get("Message"), (reply.getFields() != null) ? reply.getFields().get("Message") : null });
392 if ((reply.getFields() == null) || "Error".equals(reply.getFields().get("Message"))) {
393 throw new PluginException("Could not perform request for " + fields.get("Message"));
399 // INTERFACE ConnectorListener
406 public void receivedReply(PluginConnector pluginConnector, SimpleFieldSet fields, Bucket data) {
407 String messageName = fields.get("Message");
408 logger.log(Level.FINEST, "Received Reply from Plugin: " + messageName);
409 synchronized (reply) {
410 reply.setFields(fields);
417 * Container for the data of the reply from a plugin.
419 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
421 private static class Reply {
423 /** The fields of the reply. */
424 private SimpleFieldSet fields;
426 /** The payload of the reply. */
429 /** Empty constructor. */
435 * Returns the fields of the reply.
437 * @return The fields of the reply
439 public SimpleFieldSet getFields() {
444 * Sets the fields of the reply.
447 * The fields of the reply
449 public void setFields(SimpleFieldSet fields) {
450 this.fields = fields;
454 * Returns the payload of the reply.
456 * @return The payload of the reply (may be {@code null})
458 @SuppressWarnings("unused")
459 public Bucket getData() {
464 * Sets the payload of the reply.
467 * The payload of the reply (may be {@code null})
469 public void setData(Bucket data) {
476 * Helper method to create {@link SimpleFieldSet}s with terser code.
478 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
480 private static class SimpleFieldSetConstructor {
482 /** The field set being created. */
483 private SimpleFieldSet simpleFieldSet;
486 * Creates a new simple field set constructor.
489 * {@code true} if the resulting simple field set should be
490 * short-lived, {@code false} otherwise
492 private SimpleFieldSetConstructor(boolean shortLived) {
493 simpleFieldSet = new SimpleFieldSet(shortLived);
501 * Returns the created simple field set.
503 * @return The created simple field set
505 public SimpleFieldSet get() {
506 return simpleFieldSet;
510 * Sets the field with the given name to the given value.
513 * The name of the fleld
515 * The value of the field
516 * @return This constructor (for method chaining)
518 public SimpleFieldSetConstructor put(String name, String value) {
519 simpleFieldSet.putOverwrite(name, value);
528 * Creates a new simple field set constructor.
530 * @return The created simple field set constructor
532 public static SimpleFieldSetConstructor create() {
537 * Creates a new simple field set constructor.
540 * {@code true} if the resulting simple field set should be
541 * short-lived, {@code false} otherwise
542 * @return The created simple field set constructor
544 public static SimpleFieldSetConstructor create(boolean shortLived) {
545 SimpleFieldSetConstructor simpleFieldSetConstructor = new SimpleFieldSetConstructor(shortLived);
546 return simpleFieldSetConstructor;