Don’t cache properties, either, and implement property manipulation.
[Sone.git] / src / main / java / net / pterodactylus / sone / freenet / wot / WebOfTrustConnector.java
1 /*
2  * Sone - WebOfTrustConnector.java - Copyright © 2010 David Roden
3  *
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.pterodactylus.sone.freenet.wot;
19
20 import java.util.Collections;
21 import java.util.HashMap;
22 import java.util.HashSet;
23 import java.util.Map;
24 import java.util.Set;
25 import java.util.logging.Level;
26 import java.util.logging.Logger;
27
28 import net.pterodactylus.util.logging.Logging;
29 import freenet.support.SimpleFieldSet;
30 import freenet.support.api.Bucket;
31
32 /**
33  * Connector for the Web of Trust plugin.
34  *
35  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
36  */
37 public class WebOfTrustConnector implements ConnectorListener {
38
39         /** The logger. */
40         private static final Logger logger = Logging.getLogger(WebOfTrustConnector.class);
41
42         /** The name of the WoT plugin. */
43         private static final String WOT_PLUGIN_NAME = "plugins.WoT.WoT";
44
45         /** A random connection identifier. */
46         private static final String PLUGIN_CONNECTION_IDENTIFIER = "Sone-WoT-Connector-" + Math.abs(Math.random());
47
48         /** The current replies that we wait for. */
49         private final Map<String, Reply> replies = Collections.synchronizedMap(new HashMap<String, Reply>());
50
51         /** The plugin connector. */
52         private final PluginConnector pluginConnector;
53
54         /**
55          * Creates a new Web of Trust connector that uses the given plugin
56          * connector.
57          *
58          * @param pluginConnector
59          *            The plugin connector
60          */
61         public WebOfTrustConnector(PluginConnector pluginConnector) {
62                 this.pluginConnector = pluginConnector;
63                 pluginConnector.addConnectorListener(WOT_PLUGIN_NAME, PLUGIN_CONNECTION_IDENTIFIER, this);
64         }
65
66         //
67         // ACTIONS
68         //
69
70         /**
71          * Loads all own identities from the Web of Trust plugin.
72          *
73          * @return All own identity
74          * @throws PluginException
75          *             if the own identities can not be loaded
76          */
77         public Set<OwnIdentity> loadAllOwnIdentities() throws PluginException {
78                 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetOwnIdentities").get(), "OwnIdentities");
79                 SimpleFieldSet fields = reply.getFields();
80                 int ownIdentityCounter = -1;
81                 Set<OwnIdentity> ownIdentities = new HashSet<OwnIdentity>();
82                 while (true) {
83                         String id = fields.get("Identity" + ++ownIdentityCounter);
84                         if (id == null) {
85                                 break;
86                         }
87                         String requestUri = fields.get("RequestURI" + ownIdentityCounter);
88                         String insertUri = fields.get("InsertURI" + ownIdentityCounter);
89                         String nickname = fields.get("Nickname" + ownIdentityCounter);
90                         OwnIdentity ownIdentity = new OwnIdentity(this, id, nickname, requestUri, insertUri);
91                         ownIdentities.add(ownIdentity);
92                 }
93                 return ownIdentities;
94         }
95
96         /**
97          * Loads the contexts of the given identity.
98          *
99          * @param identity
100          *            The identity to load the contexts for
101          * @return The contexts of the identity
102          * @throws PluginException
103          *             if an error occured talking to the Web of Trust plugin
104          */
105         public Set<String> loadIdentityContexts(Identity identity) throws PluginException {
106                 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentity").put("TreeOwner", identity.getId()).put("Identity", identity.getId()).get(), "Identity");
107                 SimpleFieldSet fields = reply.getFields();
108                 int contextCounter = -1;
109                 Set<String> contexts = new HashSet<String>();
110                 while (true) {
111                         String context = fields.get("Context" + ++contextCounter);
112                         if (context == null) {
113                                 break;
114                         }
115                         contexts.add(context);
116                 }
117                 return contexts;
118         }
119
120         /**
121          * Loads all identities that the given identities trusts with a score of
122          * more than 0.
123          *
124          * @param ownIdentity
125          *            The own identity
126          * @return All trusted identities
127          * @throws PluginException
128          *             if an error occured talking to the Web of Trust plugin
129          */
130         public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity) throws PluginException {
131                 return loadTrustedIdentities(ownIdentity, null);
132         }
133
134         /**
135          * Loads all identities that the given identities trusts with a score of
136          * more than 0 and the (optional) given context.
137          *
138          * @param ownIdentity
139          *            The own identity
140          * @param context
141          *            The context to filter, or {@code null}
142          * @return All trusted identities
143          * @throws PluginException
144          *             if an error occured talking to the Web of Trust plugin
145          */
146         public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity, String context) throws PluginException {
147                 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentitiesByScore").put("TreeOwner", ownIdentity.getId()).put("Selection", "+").put("Context", (context == null) ? "" : context).get(), "Identities");
148                 SimpleFieldSet fields = reply.getFields();
149                 Set<Identity> identities = new HashSet<Identity>();
150                 int identityCounter = -1;
151                 while (true) {
152                         String id = fields.get("Identity" + ++identityCounter);
153                         if (id == null) {
154                                 break;
155                         }
156                         String nickname = fields.get("Nickname" + identityCounter);
157                         String requestUri = fields.get("RequestURI" + identityCounter);
158                         identities.add(new Identity(this, id, nickname, requestUri));
159                 }
160                 return identities;
161         }
162
163         /**
164          * Adds the given context to the given identity.
165          *
166          * @param ownIdentity
167          *            The identity to add the context to
168          * @param context
169          *            The context to add
170          * @throws PluginException
171          *             if an error occured talking to the Web of Trust plugin
172          */
173         public void addContext(OwnIdentity ownIdentity, String context) throws PluginException {
174                 performRequest(SimpleFieldSetConstructor.create().put("Message", "AddContext").put("Identity", ownIdentity.getId()).put("Context", context).get(), "ContextAdded");
175         }
176
177         /**
178          * Removes the given context from the given identity.
179          *
180          * @param ownIdentity
181          *            The identity to remove the context from
182          * @param context
183          *            The context to remove
184          * @throws PluginException
185          *             if an error occured talking to the Web of Trust plugin
186          */
187         public void removeContext(OwnIdentity ownIdentity, String context) throws PluginException {
188                 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveContext").put("Identity", ownIdentity.getId()).put("Context", context).get(), "ContextRemoved");
189         }
190
191         /**
192          * Returns the value of the property with the given name.
193          *
194          * @param identity
195          *            The identity whose properties to check
196          * @param name
197          *            The name of the property to return
198          * @return The value of the property, or {@code null} if there is no value
199          * @throws PluginException
200          *             if an error occured talking to the Web of Trust plugin
201          */
202         public String getProperty(Identity identity, String name) throws PluginException {
203                 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetProperty").put("Identity", identity.getId()).put("Property", name).get(), "PropertyValue", "Error");
204                 return reply.getFields().get("Property");
205         }
206
207         /**
208          * Sets the property with the given name to the given value.
209          *
210          * @param ownIdentity
211          *            The identity to set the property on
212          * @param name
213          *            The name of the property to set
214          * @param value
215          *            The value to set
216          * @throws PluginException
217          *             if an error occured talking to the Web of Trust plugin
218          */
219         public void setProperty(OwnIdentity ownIdentity, String name, String value) throws PluginException {
220                 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetProperty").put("Identity", ownIdentity.getId()).put("Property", name).put("Value", value).get(), "PropertyAdded");
221         }
222
223         /**
224          * Removes the property with the given name.
225          *
226          * @param ownIdentity
227          *            The identity to remove the property from
228          * @param name
229          *            The name of the property to remove
230          * @throws PluginException
231          *             if an error occured talking to the Web of Trust plugin
232          */
233         public void removeProperty(OwnIdentity ownIdentity, String name) throws PluginException {
234                 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveProperty").put("Identity", ownIdentity.getId()).put("Property", name).get(), "PropertyRemoved");
235         }
236
237         //
238         // PRIVATE ACTIONS
239         //
240
241         /**
242          * Sends a request containing the given fields and waits for the target
243          * message.
244          *
245          * @param fields
246          *            The fields of the message
247          * @param targetMessages
248          *            The messages of the reply to wait for
249          * @return The reply message
250          * @throws PluginException
251          *             if the request could not be sent
252          */
253         private Reply performRequest(SimpleFieldSet fields, String... targetMessages) throws PluginException {
254                 return performRequest(fields, null, targetMessages);
255         }
256
257         /**
258          * Sends a request containing the given fields and waits for the target
259          * message.
260          *
261          * @param fields
262          *            The fields of the message
263          * @param data
264          *            The payload of the message
265          * @param targetMessages
266          *            The messages of the reply to wait for
267          * @return The reply message
268          * @throws PluginException
269          *             if the request could not be sent
270          */
271         private Reply performRequest(SimpleFieldSet fields, Bucket data, String... targetMessages) throws PluginException {
272                 @SuppressWarnings("synthetic-access")
273                 Reply reply = new Reply();
274                 for (String targetMessage : targetMessages) {
275                         replies.put(targetMessage, reply);
276                 }
277                 synchronized (reply) {
278                         pluginConnector.sendRequest(WOT_PLUGIN_NAME, PLUGIN_CONNECTION_IDENTIFIER, fields, data);
279                         try {
280                                 reply.wait();
281                         } catch (InterruptedException ie1) {
282                                 logger.log(Level.WARNING, "Got interrupted while waiting for reply on GetOwnIdentities.", ie1);
283                         }
284                 }
285                 for (String targetMessage : targetMessages) {
286                         replies.remove(targetMessage);
287                 }
288                 return reply;
289         }
290
291         //
292         // INTERFACE ConnectorListener
293         //
294
295         /**
296          * {@inheritDoc}
297          */
298         @Override
299         public void receivedReply(PluginConnector pluginConnector, SimpleFieldSet fields, Bucket data) {
300                 String messageName = fields.get("Message");
301                 Reply reply = replies.remove(messageName);
302                 if (reply == null) {
303                         logger.log(Level.FINE, "Not waiting for a “%s” message.", messageName);
304                         return;
305                 }
306                 synchronized (reply) {
307                         reply.setFields(fields);
308                         reply.setData(data);
309                         reply.notify();
310                 }
311         }
312
313         /**
314          * Container for the data of the reply from a plugin.
315          *
316          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
317          */
318         private static class Reply {
319
320                 /** The fields of the reply. */
321                 private SimpleFieldSet fields;
322
323                 /** The payload of the reply. */
324                 private Bucket data;
325
326                 /**
327                  * Returns the fields of the reply.
328                  *
329                  * @return The fields of the reply
330                  */
331                 public SimpleFieldSet getFields() {
332                         return fields;
333                 }
334
335                 /**
336                  * Sets the fields of the reply.
337                  *
338                  * @param fields
339                  *            The fields of the reply
340                  */
341                 public void setFields(SimpleFieldSet fields) {
342                         this.fields = fields;
343                 }
344
345                 /**
346                  * Returns the payload of the reply.
347                  *
348                  * @return The payload of the reply (may be {@code null})
349                  */
350                 @SuppressWarnings("unused")
351                 public Bucket getData() {
352                         return data;
353                 }
354
355                 /**
356                  * Sets the payload of the reply.
357                  *
358                  * @param data
359                  *            The payload of the reply (may be {@code null})
360                  */
361                 public void setData(Bucket data) {
362                         this.data = data;
363                 }
364
365         }
366
367         /**
368          * Helper method to create {@link SimpleFieldSet}s with terser code.
369          *
370          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
371          */
372         private static class SimpleFieldSetConstructor {
373
374                 /** The field set being created. */
375                 private SimpleFieldSet simpleFieldSet;
376
377                 /**
378                  * Creates a new simple field set constructor.
379                  *
380                  * @param shortLived
381                  *            {@code true} if the resulting simple field set should be
382                  *            short-lived, {@code false} otherwise
383                  */
384                 private SimpleFieldSetConstructor(boolean shortLived) {
385                         simpleFieldSet = new SimpleFieldSet(shortLived);
386                 }
387
388                 //
389                 // ACCESSORS
390                 //
391
392                 /**
393                  * Returns the created simple field set.
394                  *
395                  * @return The created simple field set
396                  */
397                 public SimpleFieldSet get() {
398                         return simpleFieldSet;
399                 }
400
401                 /**
402                  * Sets the field with the given name to the given value.
403                  *
404                  * @param name
405                  *            The name of the fleld
406                  * @param value
407                  *            The value of the field
408                  * @return This constructor (for method chaining)
409                  */
410                 public SimpleFieldSetConstructor put(String name, String value) {
411                         simpleFieldSet.putOverwrite(name, value);
412                         return this;
413                 }
414
415                 //
416                 // ACTIONS
417                 //
418
419                 /**
420                  * Creates a new simple field set constructor.
421                  *
422                  * @return The created simple field set constructor
423                  */
424                 public static SimpleFieldSetConstructor create() {
425                         return create(true);
426                 }
427
428                 /**
429                  * Creates a new simple field set constructor.
430                  *
431                  * @param shortLived
432                  *            {@code true} if the resulting simple field set should be
433                  *            short-lived, {@code false} otherwise
434                  * @return The created simple field set constructor
435                  */
436                 public static SimpleFieldSetConstructor create(boolean shortLived) {
437                         SimpleFieldSetConstructor simpleFieldSetConstructor = new SimpleFieldSetConstructor(shortLived);
438                         return simpleFieldSetConstructor;
439                 }
440
441         }
442
443 }