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(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 * Sets the trust for the given identity.
225 * The trusting identity
227 * The trusted identity
229 * The amount of trust (-100 thru 100)
231 * The comment or explanation of the trust value
232 * @throws PluginException
233 * if an error occured talking to the Web of Trust plugin
235 public void setTrust(OwnIdentity ownIdentity, Identity identity, int trust, String comment) throws PluginException {
236 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).put("Value", String.valueOf(trust)).put("Comment", comment).get(), "TrustSet");
240 * Pings the Web of Trust plugin. If the plugin can not be reached, a
241 * {@link PluginException} is thrown.
243 * @throws PluginException
244 * if the plugin is not loaded
246 public void ping() throws PluginException {
247 performRequest(SimpleFieldSetConstructor.create().put("Message", "Ping").get(), "Pong");
255 * Parses the contexts from the given fields.
258 * The prefix to use to access the contexts
260 * The fields to parse the contexts from
261 * @return The parsed contexts
263 private Set<String> parseContexts(String prefix, SimpleFieldSet fields) {
264 Set<String> contexts = new HashSet<String>();
265 int contextCounter = -1;
267 String context = fields.get(prefix + "Context" + ++contextCounter);
268 if (context == null) {
271 contexts.add(context);
277 * Parses the properties from the given fields.
280 * The prefix to use to access the properties
282 * The fields to parse the properties from
283 * @return The parsed properties
285 private Map<String, String> parseProperties(String prefix, SimpleFieldSet fields) {
286 Map<String, String> properties = new HashMap<String, String>();
287 int propertiesCounter = -1;
289 String propertyName = fields.get(prefix + "Property" + ++propertiesCounter + ".Name");
290 if (propertyName == null) {
293 String propertyValue = fields.get(prefix + "Property" + propertiesCounter + ".Value");
294 properties.put(propertyName, propertyValue);
300 * Sends a request containing the given fields and waits for the target
304 * The fields of the message
305 * @param targetMessages
306 * The messages of the reply to wait for
307 * @return The reply message
308 * @throws PluginException
309 * if the request could not be sent
311 private Reply performRequest(SimpleFieldSet fields, String... targetMessages) throws PluginException {
312 return performRequest(fields, null, targetMessages);
316 * Sends a request containing the given fields and waits for the target
320 * The fields of the message
322 * The payload of the message
323 * @param targetMessages
324 * The messages of the reply to wait for
325 * @return The reply message
326 * @throws PluginException
327 * if the request could not be sent
329 private Reply performRequest(SimpleFieldSet fields, Bucket data, String... targetMessages) throws PluginException {
330 @SuppressWarnings("synthetic-access")
331 Reply reply = new Reply();
332 for (String targetMessage : targetMessages) {
333 replies.put(targetMessage, reply);
335 replies.put("Error", reply);
336 synchronized (reply) {
337 pluginConnector.sendRequest(WOT_PLUGIN_NAME, PLUGIN_CONNECTION_IDENTIFIER, fields, data);
339 long now = System.currentTimeMillis();
340 while ((reply.getFields() == null) && ((System.currentTimeMillis() - now) < 60000)) {
341 reply.wait(60000 - (System.currentTimeMillis() - now));
343 if (reply.getFields() == null) {
344 for (String targetMessage : targetMessages) {
345 replies.remove(targetMessage);
347 replies.remove("Error");
348 throw new PluginException("Timeout waiting for " + targetMessages[0] + "!");
350 } catch (InterruptedException ie1) {
351 logger.log(Level.WARNING, "Got interrupted while waiting for reply on " + targetMessages[0] + ".", ie1);
354 for (String targetMessage : targetMessages) {
355 replies.remove(targetMessage);
357 replies.remove("Error");
358 if ((reply.getFields() != null) && reply.getFields().get("Message").equals("Error")) {
359 throw new PluginException("Could not perform request for " + targetMessages[0]);
365 // INTERFACE ConnectorListener
372 public void receivedReply(PluginConnector pluginConnector, SimpleFieldSet fields, Bucket data) {
373 String messageName = fields.get("Message");
374 logger.log(Level.FINEST, "Received Reply from Plugin: " + messageName);
375 Reply reply = replies.remove(messageName);
377 logger.log(Level.FINE, "Not waiting for a “%s” message.", messageName);
380 synchronized (reply) {
381 reply.setFields(fields);
388 * Container for the data of the reply from a plugin.
390 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
392 private static class Reply {
394 /** The fields of the reply. */
395 private SimpleFieldSet fields;
397 /** The payload of the reply. */
401 * Returns the fields of the reply.
403 * @return The fields of the reply
405 public SimpleFieldSet getFields() {
410 * Sets the fields of the reply.
413 * The fields of the reply
415 public void setFields(SimpleFieldSet fields) {
416 this.fields = fields;
420 * Returns the payload of the reply.
422 * @return The payload of the reply (may be {@code null})
424 @SuppressWarnings("unused")
425 public Bucket getData() {
430 * Sets the payload of the reply.
433 * The payload of the reply (may be {@code null})
435 public void setData(Bucket data) {
442 * Helper method to create {@link SimpleFieldSet}s with terser code.
444 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
446 private static class SimpleFieldSetConstructor {
448 /** The field set being created. */
449 private SimpleFieldSet simpleFieldSet;
452 * Creates a new simple field set constructor.
455 * {@code true} if the resulting simple field set should be
456 * short-lived, {@code false} otherwise
458 private SimpleFieldSetConstructor(boolean shortLived) {
459 simpleFieldSet = new SimpleFieldSet(shortLived);
467 * Returns the created simple field set.
469 * @return The created simple field set
471 public SimpleFieldSet get() {
472 return simpleFieldSet;
476 * Sets the field with the given name to the given value.
479 * The name of the fleld
481 * The value of the field
482 * @return This constructor (for method chaining)
484 public SimpleFieldSetConstructor put(String name, String value) {
485 simpleFieldSet.putOverwrite(name, value);
494 * Creates a new simple field set constructor.
496 * @return The created simple field set constructor
498 public static SimpleFieldSetConstructor create() {
503 * Creates a new simple field set constructor.
506 * {@code true} if the resulting simple field set should be
507 * short-lived, {@code false} otherwise
508 * @return The created simple field set constructor
510 public static SimpleFieldSetConstructor create(boolean shortLived) {
511 SimpleFieldSetConstructor simpleFieldSetConstructor = new SimpleFieldSetConstructor(shortLived);
512 return simpleFieldSetConstructor;