cfb99322ab69834ae229f65f0e11676aa0d94856
[Sone.git] / src / main / java / net / pterodactylus / sone / core / WebOfTrustUpdater.java
1 /*
2  * Sone - WebOfTrustUpdater.java - Copyright © 2012 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.core;
19
20 import java.util.concurrent.BlockingQueue;
21 import java.util.concurrent.LinkedBlockingQueue;
22 import java.util.logging.Level;
23 import java.util.logging.Logger;
24
25 import net.pterodactylus.sone.freenet.plugin.PluginException;
26 import net.pterodactylus.sone.freenet.wot.DefaultIdentity;
27 import net.pterodactylus.sone.freenet.wot.Identity;
28 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
29 import net.pterodactylus.sone.freenet.wot.Trust;
30 import net.pterodactylus.sone.freenet.wot.WebOfTrustConnector;
31 import net.pterodactylus.sone.freenet.wot.WebOfTrustException;
32 import net.pterodactylus.util.logging.Logging;
33 import net.pterodactylus.util.service.AbstractService;
34
35 /**
36  * Updates WebOfTrust identity data in a background thread because communicating
37  * with the WebOfTrust plugin can potentially last quite long.
38  *
39  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
40  */
41 public class WebOfTrustUpdater extends AbstractService {
42
43         /** The logger. */
44         private static final Logger logger = Logging.getLogger(WebOfTrustUpdater.class);
45
46         /** Stop job. */
47         @SuppressWarnings("synthetic-access")
48         private final WebOfTrustUpdateJob stopJob = new WebOfTrustUpdateJob();
49
50         /** The web of trust connector. */
51         private final WebOfTrustConnector webOfTrustConnector;
52
53         /** The queue for jobs. */
54         private final BlockingQueue<WebOfTrustUpdateJob> updateJobs = new LinkedBlockingQueue<WebOfTrustUpdateJob>();
55
56         /**
57          * Creates a new trust updater.
58          *
59          * @param webOfTrustConnector
60          *            The web of trust connector
61          */
62         public WebOfTrustUpdater(WebOfTrustConnector webOfTrustConnector) {
63                 super("Trust Updater");
64                 this.webOfTrustConnector = webOfTrustConnector;
65         }
66
67         //
68         // ACTIONS
69         //
70
71         /**
72          * Retrieves the trust relation between the truster and the trustee. This
73          * method will return immediately and perform a trust update in the
74          * background.
75          *
76          * @param truster
77          *            The identity giving the trust
78          * @param trustee
79          *            The identity receiving the trust
80          */
81         public void getTrust(OwnIdentity truster, Identity trustee) {
82                 GetTrustJob getTrustJob = new GetTrustJob(truster, trustee);
83                 if (!updateJobs.contains(getTrustJob)) {
84                         logger.log(Level.FINER, "Adding Trust Update Job: " + getTrustJob);
85                         try {
86                                 updateJobs.put(getTrustJob);
87                         } catch (InterruptedException ie1) {
88                                 /* the queue is unbounded so it should never block. */
89                         }
90                 }
91         }
92
93         /**
94          * Updates the trust relation between the truster and the trustee. This
95          * method will return immediately and perform a trust update in the
96          * background.
97          *
98          * @param truster
99          *            The identity giving the trust
100          * @param trustee
101          *            The identity receiving the trust
102          * @param score
103          *            The new level of trust (from -100 to 100, may be {@code null}
104          *            to remove the trust completely)
105          * @param comment
106          *            The comment of the trust relation
107          */
108         public void setTrust(OwnIdentity truster, Identity trustee, Integer score, String comment) {
109                 SetTrustJob setTrustJob = new SetTrustJob(truster, trustee, score, comment);
110                 if (updateJobs.contains(setTrustJob)) {
111                         updateJobs.remove(setTrustJob);
112                 }
113                 logger.log(Level.FINER, "Adding Trust Update Job: " + setTrustJob);
114                 try {
115                         updateJobs.put(setTrustJob);
116                 } catch (InterruptedException e) {
117                         /* the queue is unbounded so it should never block. */
118                 }
119         }
120
121         //
122         // SERVICE METHODS
123         //
124
125         /**
126          * {@inheritDoc}
127          */
128         @Override
129         protected void serviceRun() {
130                 while (!shouldStop()) {
131                         try {
132                                 WebOfTrustUpdateJob updateJob = updateJobs.take();
133                                 if (shouldStop() || (updateJob == stopJob)) {
134                                         break;
135                                 }
136                                 logger.log(Level.FINE, "Running Trust Update Job: " + updateJob);
137                                 long startTime = System.currentTimeMillis();
138                                 updateJob.run();
139                                 long endTime = System.currentTimeMillis();
140                                 logger.log(Level.FINE, "Trust Update Job finished, took " + (endTime - startTime) + " ms.");
141                         } catch (InterruptedException ie1) {
142                                 /* happens, ignore, loop. */
143                         }
144                 }
145         }
146
147         /**
148          * {@inheritDoc}
149          */
150         @Override
151         protected void serviceStop() {
152                 try {
153                         updateJobs.put(stopJob);
154                 } catch (InterruptedException ie1) {
155                         /* the queue is unbounded so it should never block. */
156                 }
157         }
158
159         /**
160          * Base class for WebOfTrust update jobs.
161          *
162          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
163          */
164         private class WebOfTrustUpdateJob {
165
166                 /** Object for synchronization. */
167                 @SuppressWarnings("hiding")
168                 private final Object syncObject = new Object();
169
170                 /** Whether the job has finished. */
171                 private boolean finished;
172
173                 //
174                 // ACTIONS
175                 //
176
177                 /**
178                  * Performs the actual update operation.
179                  * <p>
180                  * The implementation of this class does nothing.
181                  */
182                 public void run() {
183                         /* does nothing. */
184                 }
185
186                 /**
187                  * Waits for completion of this job or stopping of the WebOfTrust
188                  * updater.
189                  *
190                  * @see WebOfTrustUpdater#stop()
191                  */
192                 @SuppressWarnings("synthetic-access")
193                 public void waitForCompletion() {
194                         synchronized (syncObject) {
195                                 while (!finished && !shouldStop()) {
196                                         try {
197                                                 syncObject.wait();
198                                         } catch (InterruptedException ie1) {
199                                                 /* we’re looping, ignore. */
200                                         }
201                                 }
202                         }
203                 }
204
205                 //
206                 // PROTECTED METHODS
207                 //
208
209                 /**
210                  * Signals that this job has finished.
211                  */
212                 protected void finish() {
213                         synchronized (syncObject) {
214                                 finished = true;
215                                 syncObject.notifyAll();
216                         }
217                 }
218
219         }
220
221         /**
222          * Base class for WebOfTrust trust update jobs.
223          *
224          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
225          */
226         private class WebOfTrustTrustUpdateJob extends WebOfTrustUpdateJob {
227
228                 /** The identity giving the trust. */
229                 protected final OwnIdentity truster;
230
231                 /** The identity receiving the trust. */
232                 protected final Identity trustee;
233
234                 /**
235                  * Creates a new trust update job.
236                  *
237                  * @param truster
238                  *            The identity giving the trust
239                  * @param trustee
240                  *            The identity receiving the trust
241                  */
242                 @SuppressWarnings("synthetic-access")
243                 public WebOfTrustTrustUpdateJob(OwnIdentity truster, Identity trustee) {
244                         this.truster = truster;
245                         this.trustee = trustee;
246                 }
247
248                 //
249                 // OBJECT METHODS
250                 //
251
252                 /**
253                  * {@inheritDoc}
254                  */
255                 @Override
256                 public boolean equals(Object object) {
257                         if ((object == null) || !object.getClass().equals(getClass())) {
258                                 return false;
259                         }
260                         WebOfTrustTrustUpdateJob updateJob = (WebOfTrustTrustUpdateJob) object;
261                         return ((truster == null) ? (updateJob.truster == null) : updateJob.truster.equals(truster)) && ((trustee == null) ? (updateJob.trustee == null) : updateJob.trustee.equals(trustee));
262                 }
263
264                 /**
265                  * {@inheritDoc}
266                  */
267                 @Override
268                 public int hashCode() {
269                         return getClass().hashCode() ^ ((truster == null) ? 0 : truster.hashCode()) ^ ((trustee == null) ? 0 : trustee.hashCode());
270                 }
271
272                 /**
273                  * {@inheritDoc}
274                  */
275                 @Override
276                 public String toString() {
277                         return String.format("%s[truster=%s,trustee=%s]", getClass().getSimpleName(), (truster == null) ? null : truster.getId(), (trustee == null) ? null : trustee.getId());
278                 }
279
280         }
281
282         /**
283          * Update job that sets the trust relation between two identities.
284          *
285          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
286          */
287         private class SetTrustJob extends WebOfTrustTrustUpdateJob {
288
289                 /** The score of the relation. */
290                 private final Integer score;
291
292                 /** The comment of the relation. */
293                 private final String comment;
294
295                 /**
296                  * Creates a new set trust job.
297                  *
298                  * @param truster
299                  *            The identity giving the trust
300                  * @param trustee
301                  *            The identity receiving the trust
302                  * @param score
303                  *            The score of the trust (from -100 to 100, may be
304                  *            {@code null} to remote the trust relation completely)
305                  * @param comment
306                  *            The comment of the trust relation
307                  */
308                 public SetTrustJob(OwnIdentity truster, Identity trustee, Integer score, String comment) {
309                         super(truster, trustee);
310                         this.score = score;
311                         this.comment = comment;
312                 }
313
314                 /**
315                  * {@inheritDoc}
316                  */
317                 @Override
318                 @SuppressWarnings("synthetic-access")
319                 public void run() {
320                         try {
321                                 if (score != null) {
322                                         if (trustee instanceof DefaultIdentity) {
323                                                 ((DefaultIdentity) trustee).setTrust(truster, new Trust(score, null, 0));
324                                         }
325                                         webOfTrustConnector.setTrust(truster, trustee, score, comment);
326                                 } else {
327                                         if (trustee instanceof DefaultIdentity) {
328                                                 ((DefaultIdentity) trustee).setTrust(truster, null);
329                                         }
330                                         webOfTrustConnector.removeTrust(truster, trustee);
331                                 }
332                         } catch (WebOfTrustException wote1) {
333                                 logger.log(Level.WARNING, "Could not set Trust value for " + truster + " -> " + trustee + " to " + score + " (" + comment + ")!", wote1);
334                         }
335                         finish();
336                 }
337
338         }
339
340         /**
341          * Update job that retrieves the trust relation between two identities.
342          *
343          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
344          */
345         private class GetTrustJob extends WebOfTrustTrustUpdateJob {
346
347                 /**
348                  * Creates a new trust update job.
349                  *
350                  * @param truster
351                  *            The identity giving the trust
352                  * @param trustee
353                  *            The identity receiving the trust
354                  */
355                 public GetTrustJob(OwnIdentity truster, Identity trustee) {
356                         super(truster, trustee);
357                 }
358
359                 /**
360                  * {@inheritDoc}
361                  */
362                 @Override
363                 @SuppressWarnings("synthetic-access")
364                 public void run() {
365                         try {
366                                 Trust trust = webOfTrustConnector.getTrust(truster, trustee);
367                                 if (trustee instanceof DefaultIdentity) {
368                                         ((DefaultIdentity) trustee).setTrust(truster, trust);
369                                 }
370                         } catch (PluginException pe1) {
371                                 logger.log(Level.WARNING, "Could not get Trust value for " + truster + " -> " + trustee + "!", pe1);
372                         }
373                         finish();
374                 }
375         }
376
377 }