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.WoT.WoT";
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 * Loads all own identities from the Web of Trust plugin.
75 * @return All own identity
76 * @throws WebOfTrustException
77 * if the own identities can not be loaded
79 public Set<OwnIdentity> loadAllOwnIdentities() throws WebOfTrustException {
80 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetOwnIdentities").get());
81 SimpleFieldSet fields = reply.getFields();
82 int ownIdentityCounter = -1;
83 Set<OwnIdentity> ownIdentities = new HashSet<OwnIdentity>();
85 String id = fields.get("Identity" + ++ownIdentityCounter);
89 String requestUri = fields.get("RequestURI" + ownIdentityCounter);
90 String insertUri = fields.get("InsertURI" + ownIdentityCounter);
91 String nickname = fields.get("Nickname" + ownIdentityCounter);
92 DefaultOwnIdentity ownIdentity = new DefaultOwnIdentity(this, id, nickname, requestUri, insertUri);
93 ownIdentity.setContextsPrivate(parseContexts("Contexts" + ownIdentityCounter + ".", fields));
94 ownIdentity.setPropertiesPrivate(parseProperties("Properties" + ownIdentityCounter + ".", fields));
95 ownIdentities.add(ownIdentity);
101 * Loads all identities that the given identities trusts with a score of
106 * @return All trusted identities
107 * @throws PluginException
108 * if an error occured talking to the Web of Trust plugin
110 public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity) throws PluginException {
111 return loadTrustedIdentities(ownIdentity, null);
115 * Loads all identities that the given identities trusts with a score of
116 * more than 0 and the (optional) given context.
121 * The context to filter, or {@code null}
122 * @return All trusted identities
123 * @throws PluginException
124 * if an error occured talking to the Web of Trust plugin
126 public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity, String context) throws PluginException {
127 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentitiesByScore").put("TreeOwner", ownIdentity.getId()).put("Selection", "+").put("Context", (context == null) ? "" : context).get());
128 SimpleFieldSet fields = reply.getFields();
129 Set<Identity> identities = new HashSet<Identity>();
130 int identityCounter = -1;
132 String id = fields.get("Identity" + ++identityCounter);
136 String nickname = fields.get("Nickname" + identityCounter);
137 String requestUri = fields.get("RequestURI" + identityCounter);
138 DefaultIdentity identity = new DefaultIdentity(this, id, nickname, requestUri);
139 identity.setContextsPrivate(parseContexts("Contexts" + identityCounter + ".", fields));
140 identity.setPropertiesPrivate(parseProperties("Properties" + identityCounter + ".", fields));
141 identities.add(identity);
147 * Adds the given context to the given identity.
150 * The identity to add the context to
153 * @throws PluginException
154 * if an error occured talking to the Web of Trust plugin
156 public void addContext(OwnIdentity ownIdentity, String context) throws PluginException {
157 performRequest(SimpleFieldSetConstructor.create().put("Message", "AddContext").put("Identity", ownIdentity.getId()).put("Context", context).get());
161 * Removes the given context from the given identity.
164 * The identity to remove the context from
166 * The context to remove
167 * @throws PluginException
168 * if an error occured talking to the Web of Trust plugin
170 public void removeContext(OwnIdentity ownIdentity, String context) throws PluginException {
171 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveContext").put("Identity", ownIdentity.getId()).put("Context", context).get());
175 * Returns the value of the property with the given name.
178 * The identity whose properties to check
180 * The name of the property to return
181 * @return The value of the property, or {@code null} if there is no value
182 * @throws PluginException
183 * if an error occured talking to the Web of Trust plugin
185 public String getProperty(Identity identity, String name) throws PluginException {
186 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetProperty").put("Identity", identity.getId()).put("Property", name).get());
187 return reply.getFields().get("Property");
191 * Sets the property with the given name to the given value.
194 * The identity to set the property on
196 * The name of the property to set
199 * @throws PluginException
200 * if an error occured talking to the Web of Trust plugin
202 public void setProperty(OwnIdentity ownIdentity, String name, String value) throws PluginException {
203 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetProperty").put("Identity", ownIdentity.getId()).put("Property", name).put("Value", value).get());
207 * Removes the property with the given name.
210 * The identity to remove the property from
212 * The name of the property to remove
213 * @throws PluginException
214 * if an error occured talking to the Web of Trust plugin
216 public void removeProperty(OwnIdentity ownIdentity, String name) throws PluginException {
217 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveProperty").put("Identity", ownIdentity.getId()).put("Property", name).get());
221 * Returns the trust for the given identity assigned to it by the given own
227 * The identity to get the trust for
228 * @return The trust for the given identity
229 * @throws PluginException
230 * if an error occured talking to the Web of Trust plugin
232 public Trust getTrust(OwnIdentity ownIdentity, Identity identity) throws PluginException {
233 Reply getTrustReply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentity").put("TreeOwner", ownIdentity.getId()).put("Identity", identity.getId()).get());
234 String trust = getTrustReply.getFields().get("Trust");
235 String score = getTrustReply.getFields().get("Score");
236 String rank = getTrustReply.getFields().get("Rank");
237 Integer explicit = null;
238 Integer implicit = null;
239 Integer distance = null;
241 explicit = Integer.valueOf(trust);
242 } catch (NumberFormatException nfe1) {
246 implicit = Integer.valueOf(score);
247 distance = Integer.valueOf(rank);
248 } catch (NumberFormatException nfe1) {
251 return new Trust(explicit, implicit, distance);
255 * Sets the trust for the given identity.
258 * The trusting identity
260 * The trusted identity
262 * The amount of trust (-100 thru 100)
264 * The comment or explanation of the trust value
265 * @throws PluginException
266 * if an error occured talking to the Web of Trust plugin
268 public void setTrust(OwnIdentity ownIdentity, Identity identity, int trust, String comment) throws PluginException {
269 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).put("Value", String.valueOf(trust)).put("Comment", comment).get());
273 * Removes any trust assignment of the given own identity for the given
279 * The identity to remove all trust for
280 * @throws WebOfTrustException
283 public void removeTrust(OwnIdentity ownIdentity, Identity identity) throws WebOfTrustException {
284 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).get());
288 * Pings the Web of Trust plugin. If the plugin can not be reached, a
289 * {@link PluginException} is thrown.
291 * @throws PluginException
292 * if the plugin is not loaded
294 public void ping() throws PluginException {
295 performRequest(SimpleFieldSetConstructor.create().put("Message", "Ping").get());
303 * Parses the contexts from the given fields.
306 * The prefix to use to access the contexts
308 * The fields to parse the contexts from
309 * @return The parsed contexts
311 private Set<String> parseContexts(String prefix, SimpleFieldSet fields) {
312 Set<String> contexts = new HashSet<String>();
313 int contextCounter = -1;
315 String context = fields.get(prefix + "Context" + ++contextCounter);
316 if (context == null) {
319 contexts.add(context);
325 * Parses the properties from the given fields.
328 * The prefix to use to access the properties
330 * The fields to parse the properties from
331 * @return The parsed properties
333 private Map<String, String> parseProperties(String prefix, SimpleFieldSet fields) {
334 Map<String, String> properties = new HashMap<String, String>();
335 int propertiesCounter = -1;
337 String propertyName = fields.get(prefix + "Property" + ++propertiesCounter + ".Name");
338 if (propertyName == null) {
341 String propertyValue = fields.get(prefix + "Property" + propertiesCounter + ".Value");
342 properties.put(propertyName, propertyValue);
348 * Sends a request containing the given fields and waits for the target
352 * The fields of the message
353 * @return The reply message
354 * @throws PluginException
355 * if the request could not be sent
357 private Reply performRequest(SimpleFieldSet fields) throws PluginException {
358 return performRequest(fields, null);
362 * Sends a request containing the given fields and waits for the target
366 * The fields of the message
368 * The payload of the message
369 * @return The reply message
370 * @throws PluginException
371 * if the request could not be sent
373 private synchronized Reply performRequest(SimpleFieldSet fields, Bucket data) throws PluginException {
375 logger.log(Level.FINE, "Sending FCP Request: " + fields.get("Message"));
376 synchronized (reply) {
377 pluginConnector.sendRequest(WOT_PLUGIN_NAME, PLUGIN_CONNECTION_IDENTIFIER, fields, data);
380 } catch (InterruptedException ie1) {
381 logger.log(Level.WARNING, "Got interrupted while waiting for reply on " + fields.get("Message") + ".", ie1);
384 logger.log(Level.FINEST, "Received FCP Response for %s: %s", new Object[] { fields.get("Message"), (reply.getFields() != null) ? reply.getFields().get("Message") : null });
385 if ((reply.getFields() == null) || "Error".equals(reply.getFields().get("Message"))) {
386 throw new PluginException("Could not perform request for " + fields.get("Message"));
392 // INTERFACE ConnectorListener
399 public void receivedReply(PluginConnector pluginConnector, SimpleFieldSet fields, Bucket data) {
400 String messageName = fields.get("Message");
401 logger.log(Level.FINEST, "Received Reply from Plugin: " + messageName);
402 synchronized (reply) {
403 reply.setFields(fields);
410 * Container for the data of the reply from a plugin.
412 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
414 private static class Reply {
416 /** The fields of the reply. */
417 private SimpleFieldSet fields;
419 /** The payload of the reply. */
422 /** Empty constructor. */
428 * Returns the fields of the reply.
430 * @return The fields of the reply
432 public SimpleFieldSet getFields() {
437 * Sets the fields of the reply.
440 * The fields of the reply
442 public void setFields(SimpleFieldSet fields) {
443 this.fields = fields;
447 * Returns the payload of the reply.
449 * @return The payload of the reply (may be {@code null})
451 @SuppressWarnings("unused")
452 public Bucket getData() {
457 * Sets the payload of the reply.
460 * The payload of the reply (may be {@code null})
462 public void setData(Bucket data) {
469 * Helper method to create {@link SimpleFieldSet}s with terser code.
471 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
473 private static class SimpleFieldSetConstructor {
475 /** The field set being created. */
476 private SimpleFieldSet simpleFieldSet;
479 * Creates a new simple field set constructor.
482 * {@code true} if the resulting simple field set should be
483 * short-lived, {@code false} otherwise
485 private SimpleFieldSetConstructor(boolean shortLived) {
486 simpleFieldSet = new SimpleFieldSet(shortLived);
494 * Returns the created simple field set.
496 * @return The created simple field set
498 public SimpleFieldSet get() {
499 return simpleFieldSet;
503 * Sets the field with the given name to the given value.
506 * The name of the fleld
508 * The value of the field
509 * @return This constructor (for method chaining)
511 public SimpleFieldSetConstructor put(String name, String value) {
512 simpleFieldSet.putOverwrite(name, value);
521 * Creates a new simple field set constructor.
523 * @return The created simple field set constructor
525 public static SimpleFieldSetConstructor create() {
530 * Creates a new simple field set constructor.
533 * {@code true} if the resulting simple field set should be
534 * short-lived, {@code false} otherwise
535 * @return The created simple field set constructor
537 public static SimpleFieldSetConstructor create(boolean shortLived) {
538 SimpleFieldSetConstructor simpleFieldSetConstructor = new SimpleFieldSetConstructor(shortLived);
539 return simpleFieldSetConstructor;