Add test for “add context” job.
[Sone.git] / src / main / java / net / pterodactylus / sone / core / WebOfTrustUpdater.java
1 /*
2  * Sone - WebOfTrustUpdater.java - Copyright © 2013 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 static com.google.common.base.Preconditions.checkNotNull;
21
22 import java.util.concurrent.BlockingQueue;
23 import java.util.concurrent.LinkedBlockingQueue;
24 import java.util.logging.Level;
25 import java.util.logging.Logger;
26
27 import net.pterodactylus.sone.freenet.plugin.PluginException;
28 import net.pterodactylus.sone.freenet.wot.DefaultIdentity;
29 import net.pterodactylus.sone.freenet.wot.Identity;
30 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
31 import net.pterodactylus.sone.freenet.wot.Trust;
32 import net.pterodactylus.sone.freenet.wot.WebOfTrustConnector;
33 import net.pterodactylus.sone.freenet.wot.WebOfTrustException;
34 import net.pterodactylus.util.logging.Logging;
35 import net.pterodactylus.util.service.AbstractService;
36
37 import com.google.common.annotations.VisibleForTesting;
38 import com.google.inject.Inject;
39
40 /**
41  * Updates WebOfTrust identity data in a background thread because communicating
42  * with the WebOfTrust plugin can potentially last quite long.
43  *
44  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
45  */
46 public class WebOfTrustUpdater extends AbstractService {
47
48         /** The logger. */
49         private static final Logger logger = Logging.getLogger(WebOfTrustUpdater.class);
50
51         /** Stop job. */
52         @SuppressWarnings("synthetic-access")
53         private final WebOfTrustUpdateJob stopJob = new WebOfTrustUpdateJob();
54
55         /** The web of trust connector. */
56         private final WebOfTrustConnector webOfTrustConnector;
57
58         /** The queue for jobs. */
59         private final BlockingQueue<WebOfTrustUpdateJob> updateJobs = new LinkedBlockingQueue<WebOfTrustUpdateJob>();
60
61         /**
62          * Creates a new trust updater.
63          *
64          * @param webOfTrustConnector
65          *              The web of trust connector
66          */
67         @Inject
68         public WebOfTrustUpdater(WebOfTrustConnector webOfTrustConnector) {
69                 super("Trust Updater");
70                 this.webOfTrustConnector = webOfTrustConnector;
71         }
72
73         //
74         // ACTIONS
75         //
76
77         /**
78          * Updates the trust relation between the truster and the trustee. This method
79          * will return immediately and perform a trust update in the background.
80          *
81          * @param truster
82          *              The identity giving the trust
83          * @param trustee
84          *              The identity receiving the trust
85          * @param score
86          *              The new level of trust (from -100 to 100, may be {@code null} to remove
87          *              the trust completely)
88          * @param comment
89          *              The comment of the trust relation
90          */
91         public void setTrust(OwnIdentity truster, Identity trustee, Integer score, String comment) {
92                 SetTrustJob setTrustJob = new SetTrustJob(truster, trustee, score, comment);
93                 if (updateJobs.contains(setTrustJob)) {
94                         updateJobs.remove(setTrustJob);
95                 }
96                 logger.log(Level.FINER, "Adding Trust Update Job: " + setTrustJob);
97                 try {
98                         updateJobs.put(setTrustJob);
99                 } catch (InterruptedException e) {
100                         /* the queue is unbounded so it should never block. */
101                 }
102         }
103
104         /**
105          * Adds the given context to the given own identity.
106          *
107          * @param ownIdentity
108          *              The own identity to add the context to
109          * @param context
110          *              The context to add
111          */
112         public void addContext(OwnIdentity ownIdentity, String context) {
113                 addContextWait(ownIdentity, context, false);
114         }
115
116         /**
117          * Adds the given context to the given own identity, waiting for completion of
118          * the operation.
119          *
120          * @param ownIdentity
121          *              The own identity to add the context to
122          * @param context
123          *              The context to add
124          * @return {@code true} if the context was added successfully, {@code false}
125          *         otherwise
126          */
127         public boolean addContextWait(OwnIdentity ownIdentity, String context) {
128                 return addContextWait(ownIdentity, context, true);
129         }
130
131         /**
132          * Adds the given context to the given own identity, waiting for completion of
133          * the operation.
134          *
135          * @param ownIdentity
136          *              The own identity to add the context to
137          * @param context
138          *              The context to add
139          * @param wait
140          *              {@code true} to wait for the end of the operation, {@code false} to return
141          *              immediately
142          * @return {@code true} if the context was added successfully, {@code false} if
143          *         the context was not added successfully, or if the job should not
144          *         wait for completion
145          */
146         private boolean addContextWait(OwnIdentity ownIdentity, String context, boolean wait) {
147                 AddContextJob addContextJob = new AddContextJob(ownIdentity, context);
148                 if (!updateJobs.contains(addContextJob)) {
149                         logger.log(Level.FINER, "Adding Context Job: " + addContextJob);
150                         try {
151                                 updateJobs.put(addContextJob);
152                         } catch (InterruptedException ie1) {
153                                 /* the queue is unbounded so it should never block. */
154                         }
155                         if (wait) {
156                                 return addContextJob.waitForCompletion();
157                         }
158                 } else if (wait) {
159                         for (WebOfTrustUpdateJob updateJob : updateJobs) {
160                                 if (updateJob.equals(addContextJob)) {
161                                         return updateJob.waitForCompletion();
162                                 }
163                         }
164                 }
165                 return false;
166         }
167
168         /**
169          * Removes the given context from the given own identity.
170          *
171          * @param ownIdentity
172          *              The own identity to remove the context from
173          * @param context
174          *              The context to remove
175          */
176         public void removeContext(OwnIdentity ownIdentity, String context) {
177                 RemoveContextJob removeContextJob = new RemoveContextJob(ownIdentity, context);
178                 if (!updateJobs.contains(removeContextJob)) {
179                         logger.log(Level.FINER, "Adding Context Job: " + removeContextJob);
180                         try {
181                                 updateJobs.put(removeContextJob);
182                         } catch (InterruptedException ie1) {
183                                 /* the queue is unbounded so it should never block. */
184                         }
185                 }
186         }
187
188         /**
189          * Sets a property on the given own identity.
190          *
191          * @param ownIdentity
192          *              The own identity to set the property on
193          * @param propertyName
194          *              The name of the property to set
195          * @param propertyValue
196          *              The value of the property to set
197          */
198         public void setProperty(OwnIdentity ownIdentity, String propertyName, String propertyValue) {
199                 SetPropertyJob setPropertyJob = new SetPropertyJob(ownIdentity, propertyName, propertyValue);
200                 if (updateJobs.contains(setPropertyJob)) {
201                         updateJobs.remove(setPropertyJob);
202                 }
203                 logger.log(Level.FINER, "Adding Property Job: " + setPropertyJob);
204                 try {
205                         updateJobs.put(setPropertyJob);
206                 } catch (InterruptedException e) {
207                         /* the queue is unbounded so it should never block. */
208                 }
209         }
210
211         /**
212          * Removes a property from the given own identity.
213          *
214          * @param ownIdentity
215          *              The own identity to remove the property from
216          * @param propertyName
217          *              The name of the property to remove
218          */
219         public void removeProperty(OwnIdentity ownIdentity, String propertyName) {
220                 setProperty(ownIdentity, propertyName, null);
221         }
222
223         //
224         // SERVICE METHODS
225         //
226
227         /** {@inheritDoc} */
228         @Override
229         protected void serviceRun() {
230                 while (!shouldStop()) {
231                         try {
232                                 WebOfTrustUpdateJob updateJob = updateJobs.take();
233                                 if (shouldStop() || (updateJob == stopJob)) {
234                                         break;
235                                 }
236                                 logger.log(Level.FINE, "Running Trust Update Job: " + updateJob);
237                                 long startTime = System.currentTimeMillis();
238                                 updateJob.run();
239                                 long endTime = System.currentTimeMillis();
240                                 logger.log(Level.FINE, "Trust Update Job finished, took " + (endTime - startTime) + " ms.");
241                         } catch (InterruptedException ie1) {
242                                 /* happens, ignore, loop. */
243                         }
244                 }
245         }
246
247         /** {@inheritDoc} */
248         @Override
249         protected void serviceStop() {
250                 try {
251                         updateJobs.put(stopJob);
252                 } catch (InterruptedException ie1) {
253                         /* the queue is unbounded so it should never block. */
254                 }
255         }
256
257         /**
258          * Base class for WebOfTrust update jobs.
259          *
260          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
261          */
262         private class WebOfTrustUpdateJob {
263
264                 /** Object for synchronization. */
265                 @SuppressWarnings("hiding")
266                 private final Object syncObject = new Object();
267
268                 /** Whether the job has finished. */
269                 private boolean finished;
270
271                 /** Whether the job was successful. */
272                 private boolean success;
273
274                 //
275                 // ACTIONS
276                 //
277
278                 /**
279                  * Performs the actual update operation.
280                  * <p/>
281                  * The implementation of this class does nothing.
282                  */
283                 public void run() {
284                         /* does nothing. */
285                 }
286
287                 /**
288                  * Waits for completion of this job or stopping of the WebOfTrust updater.
289                  *
290                  * @return {@code true} if this job finished successfully, {@code false}
291                  *         otherwise
292                  * @see WebOfTrustUpdater#stop()
293                  */
294                 @SuppressWarnings("synthetic-access")
295                 public boolean waitForCompletion() {
296                         synchronized (syncObject) {
297                                 while (!finished && !shouldStop()) {
298                                         try {
299                                                 syncObject.wait();
300                                         } catch (InterruptedException ie1) {
301                                                 /* we’re looping, ignore. */
302                                         }
303                                 }
304                                 return success;
305                         }
306                 }
307
308                 //
309                 // PROTECTED METHODS
310                 //
311
312                 /**
313                  * Signals that this job has finished.
314                  *
315                  * @param success
316                  *              {@code true} if this job finished successfully, {@code false} otherwise
317                  */
318                 protected void finish(boolean success) {
319                         synchronized (syncObject) {
320                                 finished = true;
321                                 this.success = success;
322                                 syncObject.notifyAll();
323                         }
324                 }
325
326         }
327
328         /**
329          * Update job that sets the trust relation between two identities.
330          *
331          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
332          */
333         private class SetTrustJob extends WebOfTrustUpdateJob {
334
335                 /** The identity giving the trust. */
336                 private final OwnIdentity truster;
337
338                 /** The identity receiving the trust. */
339                 private final Identity trustee;
340
341                 /** The score of the relation. */
342                 private final Integer score;
343
344                 /** The comment of the relation. */
345                 private final String comment;
346
347                 /**
348                  * Creates a new set trust job.
349                  *
350                  * @param truster
351                  *              The identity giving the trust
352                  * @param trustee
353                  *              The identity receiving the trust
354                  * @param score
355                  *              The score of the trust (from -100 to 100, may be {@code null} to remote
356                  *              the trust relation completely)
357                  * @param comment
358                  *              The comment of the trust relation
359                  */
360                 public SetTrustJob(OwnIdentity truster, Identity trustee, Integer score, String comment) {
361                         this.truster = truster;
362                         this.trustee = trustee;
363                         this.score = score;
364                         this.comment = comment;
365                 }
366
367                 /** {@inheritDoc} */
368                 @Override
369                 @SuppressWarnings("synthetic-access")
370                 public void run() {
371                         try {
372                                 if (score != null) {
373                                         if (trustee instanceof DefaultIdentity) {
374                                                 ((DefaultIdentity) trustee).setTrust(truster, new Trust(score, null, 0));
375                                         }
376                                         webOfTrustConnector.setTrust(truster, trustee, score, comment);
377                                 } else {
378                                         if (trustee instanceof DefaultIdentity) {
379                                                 ((DefaultIdentity) trustee).setTrust(truster, null);
380                                         }
381                                         webOfTrustConnector.removeTrust(truster, trustee);
382                                 }
383                                 finish(true);
384                         } catch (WebOfTrustException wote1) {
385                                 logger.log(Level.WARNING, "Could not set Trust value for " + truster + " -> " + trustee + " to " + score + " (" + comment + ")!", wote1);
386                                 finish(false);
387                         }
388                 }
389
390                 //
391                 // OBJECT METHODS
392                 //
393
394                 /** {@inheritDoc} */
395                 @Override
396                 public boolean equals(Object object) {
397                         if ((object == null) || !object.getClass().equals(getClass())) {
398                                 return false;
399                         }
400                         SetTrustJob updateJob = (SetTrustJob) object;
401                         return ((truster == null) ? (updateJob.truster == null) : updateJob.truster.equals(truster)) && ((trustee == null) ? (updateJob.trustee == null) : updateJob.trustee.equals(trustee));
402                 }
403
404                 /** {@inheritDoc} */
405                 @Override
406                 public int hashCode() {
407                         return getClass().hashCode() ^ ((truster == null) ? 0 : truster.hashCode()) ^ ((trustee == null) ? 0 : trustee.hashCode());
408                 }
409
410                 /** {@inheritDoc} */
411                 @Override
412                 public String toString() {
413                         return String.format("%s[truster=%s,trustee=%s]", getClass().getSimpleName(), (truster == null) ? null : truster.getId(), (trustee == null) ? null : trustee.getId());
414                 }
415
416         }
417
418         /**
419          * Base class for context updates of an {@link OwnIdentity}.
420          *
421          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
422          */
423         private class WebOfTrustContextUpdateJob extends WebOfTrustUpdateJob {
424
425                 /** The own identity whose contexts to manage. */
426                 protected final OwnIdentity ownIdentity;
427
428                 /** The context to update. */
429                 protected final String context;
430
431                 /**
432                  * Creates a new context update job.
433                  *
434                  * @param ownIdentity
435                  *              The own identity to update
436                  * @param context
437                  *              The context to update
438                  */
439                 @SuppressWarnings("synthetic-access")
440                 public WebOfTrustContextUpdateJob(OwnIdentity ownIdentity, String context) {
441                         this.ownIdentity = checkNotNull(ownIdentity, "ownIdentity must not be null");
442                         this.context = checkNotNull(context, "context must not be null");
443                 }
444
445                 //
446                 // OBJECT METHODS
447                 //
448
449                 /** {@inheritDoc} */
450                 @Override
451                 public boolean equals(Object object) {
452                         if ((object == null) || !object.getClass().equals(getClass())) {
453                                 return false;
454                         }
455                         WebOfTrustContextUpdateJob updateJob = (WebOfTrustContextUpdateJob) object;
456                         return updateJob.ownIdentity.equals(ownIdentity) && updateJob.context.equals(context);
457                 }
458
459                 /** {@inheritDoc} */
460                 @Override
461                 public int hashCode() {
462                         return getClass().hashCode() ^ ownIdentity.hashCode() ^ context.hashCode();
463                 }
464
465                 /** {@inheritDoc} */
466                 @Override
467                 public String toString() {
468                         return String.format("%s[ownIdentity=%s,context=%s]", getClass().getSimpleName(), ownIdentity, context);
469                 }
470
471         }
472
473         /**
474          * Job that adds a context to an {@link OwnIdentity}.
475          *
476          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
477          */
478         @VisibleForTesting
479         class AddContextJob extends WebOfTrustContextUpdateJob {
480
481                 /**
482                  * Creates a new add-context job.
483                  *
484                  * @param ownIdentity
485                  *              The own identity whose contexts to manage
486                  * @param context
487                  *              The context to add
488                  */
489                 public AddContextJob(OwnIdentity ownIdentity, String context) {
490                         super(ownIdentity, context);
491                 }
492
493                 /** {@inheritDoc} */
494                 @Override
495                 @SuppressWarnings("synthetic-access")
496                 public void run() {
497                         try {
498                                 webOfTrustConnector.addContext(ownIdentity, context);
499                                 ownIdentity.addContext(context);
500                                 finish(true);
501                         } catch (PluginException pe1) {
502                                 logger.log(Level.WARNING, String.format("Could not add Context “%2$s” to Own Identity %1$s!", ownIdentity, context), pe1);
503                                 finish(false);
504                         }
505                 }
506
507         }
508
509         /**
510          * Job that removes a context from an {@link OwnIdentity}.
511          *
512          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
513          */
514         private class RemoveContextJob extends WebOfTrustContextUpdateJob {
515
516                 /**
517                  * Creates a new remove-context job.
518                  *
519                  * @param ownIdentity
520                  *              The own identity whose contexts to manage
521                  * @param context
522                  *              The context to remove
523                  */
524                 public RemoveContextJob(OwnIdentity ownIdentity, String context) {
525                         super(ownIdentity, context);
526                 }
527
528                 /** {@inheritDoc} */
529                 @Override
530                 @SuppressWarnings("synthetic-access")
531                 public void run() {
532                         try {
533                                 webOfTrustConnector.removeContext(ownIdentity, context);
534                                 ownIdentity.removeContext(context);
535                                 finish(true);
536                         } catch (PluginException pe1) {
537                                 logger.log(Level.WARNING, String.format("Could not remove Context “%2$s” to Own Identity %1$s!", ownIdentity, context), pe1);
538                                 finish(false);
539                         }
540                 }
541
542         }
543
544         /**
545          * WebOfTrust update job that sets a property on an {@link OwnIdentity}.
546          *
547          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
548          */
549         private class SetPropertyJob extends WebOfTrustUpdateJob {
550
551                 /** The own identity to update properties on. */
552                 private final OwnIdentity ownIdentity;
553
554                 /** The name of the property to update. */
555                 private final String propertyName;
556
557                 /** The value of the property to set. */
558                 private final String propertyValue;
559
560                 /**
561                  * Creates a new set-property job.
562                  *
563                  * @param ownIdentity
564                  *              The own identity to set the property on
565                  * @param propertyName
566                  *              The name of the property to set
567                  * @param propertyValue
568                  *              The value of the property to set
569                  */
570                 public SetPropertyJob(OwnIdentity ownIdentity, String propertyName, String propertyValue) {
571                         this.ownIdentity = ownIdentity;
572                         this.propertyName = propertyName;
573                         this.propertyValue = propertyValue;
574                 }
575
576                 /** {@inheritDoc} */
577                 @Override
578                 @SuppressWarnings("synthetic-access")
579                 public void run() {
580                         try {
581                                 if (propertyValue == null) {
582                                         webOfTrustConnector.removeProperty(ownIdentity, propertyName);
583                                         ownIdentity.removeProperty(propertyName);
584                                 } else {
585                                         webOfTrustConnector.setProperty(ownIdentity, propertyName, propertyValue);
586                                         ownIdentity.setProperty(propertyName, propertyValue);
587                                 }
588                                 finish(true);
589                         } catch (PluginException pe1) {
590                                 logger.log(Level.WARNING, String.format("Could not set Property “%2$s” to “%3$s” on Own Identity %1$s!", ownIdentity, propertyName, propertyValue), pe1);
591                                 finish(false);
592                         }
593                 }
594
595                 //
596                 // OBJECT METHODS
597                 //
598
599                 /** {@inheritDoc} */
600                 @Override
601                 public boolean equals(Object object) {
602                         if ((object == null) || !object.getClass().equals(getClass())) {
603                                 return false;
604                         }
605                         SetPropertyJob updateJob = (SetPropertyJob) object;
606                         return updateJob.ownIdentity.equals(ownIdentity) && updateJob.propertyName.equals(propertyName);
607                 }
608
609                 /** {@inheritDoc} */
610                 @Override
611                 public int hashCode() {
612                         return getClass().hashCode() ^ ownIdentity.hashCode() ^ propertyName.hashCode();
613                 }
614
615                 /** {@inheritDoc} */
616                 @Override
617                 public String toString() {
618                         return String.format("%s[ownIdentity=%s,propertyName=%s]", getClass().getSimpleName(), ownIdentity, propertyName);
619                 }
620
621         }
622
623 }