Replace utils’ Validation by Guava’s Preconditions.
[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 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.inject.Inject;
38
39 /**
40  * Updates WebOfTrust identity data in a background thread because communicating
41  * with the WebOfTrust plugin can potentially last quite long.
42  *
43  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
44  */
45 public class WebOfTrustUpdater extends AbstractService {
46
47         /** The logger. */
48         private static final Logger logger = Logging.getLogger(WebOfTrustUpdater.class);
49
50         /** Stop job. */
51         @SuppressWarnings("synthetic-access")
52         private final WebOfTrustUpdateJob stopJob = new WebOfTrustUpdateJob();
53
54         /** The web of trust connector. */
55         private final WebOfTrustConnector webOfTrustConnector;
56
57         /** The queue for jobs. */
58         private final BlockingQueue<WebOfTrustUpdateJob> updateJobs = new LinkedBlockingQueue<WebOfTrustUpdateJob>();
59
60         /**
61          * Creates a new trust updater.
62          *
63          * @param webOfTrustConnector
64          *            The web of trust connector
65          */
66         @Inject
67         public WebOfTrustUpdater(WebOfTrustConnector webOfTrustConnector) {
68                 super("Trust Updater");
69                 this.webOfTrustConnector = webOfTrustConnector;
70         }
71
72         //
73         // ACTIONS
74         //
75
76         /**
77          * Updates the trust relation between the truster and the trustee. This
78          * method will return immediately and perform a trust update in the
79          * 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}
87          *            to remove 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
118          * of 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
133          * of 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,
141          *            {@code false} to return immediately
142          * @return {@code true} if the context was added successfully, {@code false}
143          *         if the context was not added successfully, or if the job should
144          *         not 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         /**
228          * {@inheritDoc}
229          */
230         @Override
231         protected void serviceRun() {
232                 while (!shouldStop()) {
233                         try {
234                                 WebOfTrustUpdateJob updateJob = updateJobs.take();
235                                 if (shouldStop() || (updateJob == stopJob)) {
236                                         break;
237                                 }
238                                 logger.log(Level.FINE, "Running Trust Update Job: " + updateJob);
239                                 long startTime = System.currentTimeMillis();
240                                 updateJob.run();
241                                 long endTime = System.currentTimeMillis();
242                                 logger.log(Level.FINE, "Trust Update Job finished, took " + (endTime - startTime) + " ms.");
243                         } catch (InterruptedException ie1) {
244                                 /* happens, ignore, loop. */
245                         }
246                 }
247         }
248
249         /**
250          * {@inheritDoc}
251          */
252         @Override
253         protected void serviceStop() {
254                 try {
255                         updateJobs.put(stopJob);
256                 } catch (InterruptedException ie1) {
257                         /* the queue is unbounded so it should never block. */
258                 }
259         }
260
261         /**
262          * Base class for WebOfTrust update jobs.
263          *
264          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
265          */
266         private class WebOfTrustUpdateJob {
267
268                 /** Object for synchronization. */
269                 @SuppressWarnings("hiding")
270                 private final Object syncObject = new Object();
271
272                 /** Whether the job has finished. */
273                 private boolean finished;
274
275                 /** Whether the job was successful. */
276                 private boolean success;
277
278                 //
279                 // ACTIONS
280                 //
281
282                 /**
283                  * Performs the actual update operation.
284                  * <p>
285                  * The implementation of this class does nothing.
286                  */
287                 public void run() {
288                         /* does nothing. */
289                 }
290
291                 /**
292                  * Waits for completion of this job or stopping of the WebOfTrust
293                  * updater.
294                  *
295                  * @return {@code true} if this job finished successfully, {@code false}
296                  *         otherwise
297                  *
298                  * @see WebOfTrustUpdater#stop()
299                  */
300                 @SuppressWarnings("synthetic-access")
301                 public boolean waitForCompletion() {
302                         synchronized (syncObject) {
303                                 while (!finished && !shouldStop()) {
304                                         try {
305                                                 syncObject.wait();
306                                         } catch (InterruptedException ie1) {
307                                                 /* we’re looping, ignore. */
308                                         }
309                                 }
310                                 return success;
311                         }
312                 }
313
314                 //
315                 // PROTECTED METHODS
316                 //
317
318                 /**
319                  * Signals that this job has finished.
320                  *
321                  * @param success
322                  *            {@code true} if this job finished successfully,
323                  *            {@code false} otherwise
324                  */
325                 protected void finish(boolean success) {
326                         synchronized (syncObject) {
327                                 finished = true;
328                                 this.success = success;
329                                 syncObject.notifyAll();
330                         }
331                 }
332
333         }
334
335         /**
336          * Base class for WebOfTrust trust update jobs.
337          *
338          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
339          */
340         private class WebOfTrustTrustUpdateJob extends WebOfTrustUpdateJob {
341
342                 /** The identity giving the trust. */
343                 protected final OwnIdentity truster;
344
345                 /** The identity receiving the trust. */
346                 protected final Identity trustee;
347
348                 /**
349                  * Creates a new trust update job.
350                  *
351                  * @param truster
352                  *            The identity giving the trust
353                  * @param trustee
354                  *            The identity receiving the trust
355                  */
356                 @SuppressWarnings("synthetic-access")
357                 public WebOfTrustTrustUpdateJob(OwnIdentity truster, Identity trustee) {
358                         this.truster = truster;
359                         this.trustee = trustee;
360                 }
361
362                 //
363                 // OBJECT METHODS
364                 //
365
366                 /**
367                  * {@inheritDoc}
368                  */
369                 @Override
370                 public boolean equals(Object object) {
371                         if ((object == null) || !object.getClass().equals(getClass())) {
372                                 return false;
373                         }
374                         WebOfTrustTrustUpdateJob updateJob = (WebOfTrustTrustUpdateJob) object;
375                         return ((truster == null) ? (updateJob.truster == null) : updateJob.truster.equals(truster)) && ((trustee == null) ? (updateJob.trustee == null) : updateJob.trustee.equals(trustee));
376                 }
377
378                 /**
379                  * {@inheritDoc}
380                  */
381                 @Override
382                 public int hashCode() {
383                         return getClass().hashCode() ^ ((truster == null) ? 0 : truster.hashCode()) ^ ((trustee == null) ? 0 : trustee.hashCode());
384                 }
385
386                 /**
387                  * {@inheritDoc}
388                  */
389                 @Override
390                 public String toString() {
391                         return String.format("%s[truster=%s,trustee=%s]", getClass().getSimpleName(), (truster == null) ? null : truster.getId(), (trustee == null) ? null : trustee.getId());
392                 }
393
394         }
395
396         /**
397          * Update job that sets the trust relation between two identities.
398          *
399          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
400          */
401         private class SetTrustJob extends WebOfTrustTrustUpdateJob {
402
403                 /** The score of the relation. */
404                 private final Integer score;
405
406                 /** The comment of the relation. */
407                 private final String comment;
408
409                 /**
410                  * Creates a new set trust job.
411                  *
412                  * @param truster
413                  *            The identity giving the trust
414                  * @param trustee
415                  *            The identity receiving the trust
416                  * @param score
417                  *            The score of the trust (from -100 to 100, may be
418                  *            {@code null} to remote the trust relation completely)
419                  * @param comment
420                  *            The comment of the trust relation
421                  */
422                 public SetTrustJob(OwnIdentity truster, Identity trustee, Integer score, String comment) {
423                         super(truster, trustee);
424                         this.score = score;
425                         this.comment = comment;
426                 }
427
428                 /**
429                  * {@inheritDoc}
430                  */
431                 @Override
432                 @SuppressWarnings("synthetic-access")
433                 public void run() {
434                         try {
435                                 if (score != null) {
436                                         if (trustee instanceof DefaultIdentity) {
437                                                 ((DefaultIdentity) trustee).setTrust(truster, new Trust(score, null, 0));
438                                         }
439                                         webOfTrustConnector.setTrust(truster, trustee, score, comment);
440                                 } else {
441                                         if (trustee instanceof DefaultIdentity) {
442                                                 ((DefaultIdentity) trustee).setTrust(truster, null);
443                                         }
444                                         webOfTrustConnector.removeTrust(truster, trustee);
445                                 }
446                                 finish(true);
447                         } catch (WebOfTrustException wote1) {
448                                 logger.log(Level.WARNING, "Could not set Trust value for " + truster + " -> " + trustee + " to " + score + " (" + comment + ")!", wote1);
449                                 finish(false);
450                         }
451                 }
452
453         }
454
455         /**
456          * Base class for context updates of an {@link OwnIdentity}.
457          *
458          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
459          */
460         private class WebOfTrustContextUpdateJob extends WebOfTrustUpdateJob {
461
462                 /** The own identity whose contexts to manage. */
463                 protected final OwnIdentity ownIdentity;
464
465                 /** The context to update. */
466                 protected final String context;
467
468                 /**
469                  * Creates a new context update job.
470                  *
471                  * @param ownIdentity
472                  *            The own identity to update
473                  * @param context
474                  *            The context to update
475                  */
476                 @SuppressWarnings("synthetic-access")
477                 public WebOfTrustContextUpdateJob(OwnIdentity ownIdentity, String context) {
478                         this.ownIdentity = checkNotNull(ownIdentity, "ownIdentity must not be null");
479                         this.context = checkNotNull(context, "context must not be null");
480                 }
481
482                 //
483                 // OBJECT METHODS
484                 //
485
486                 /**
487                  * {@inheritDoc}
488                  */
489                 @Override
490                 public boolean equals(Object object) {
491                         if ((object == null) || !object.getClass().equals(getClass())) {
492                                 return false;
493                         }
494                         WebOfTrustContextUpdateJob updateJob = (WebOfTrustContextUpdateJob) object;
495                         return updateJob.ownIdentity.equals(ownIdentity) && updateJob.context.equals(context);
496                 }
497
498                 /**
499                  * {@inheritDoc}
500                  */
501                 @Override
502                 public int hashCode() {
503                         return getClass().hashCode() ^ ownIdentity.hashCode() ^ context.hashCode();
504                 }
505
506                 /**
507                  * {@inheritDoc}
508                  */
509                 @Override
510                 public String toString() {
511                         return String.format("%s[ownIdentity=%s,context=%s]", getClass().getSimpleName(), ownIdentity, context);
512                 }
513
514         }
515
516         /**
517          * Job that adds a context to an {@link OwnIdentity}.
518          *
519          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
520          */
521         private class AddContextJob extends WebOfTrustContextUpdateJob {
522
523                 /**
524                  * Creates a new add-context job.
525                  *
526                  * @param ownIdentity
527                  *            The own identity whose contexts to manage
528                  * @param context
529                  *            The context to add
530                  */
531                 public AddContextJob(OwnIdentity ownIdentity, String context) {
532                         super(ownIdentity, context);
533                 }
534
535                 /**
536                  * {@inheritDoc}
537                  */
538                 @Override
539                 @SuppressWarnings("synthetic-access")
540                 public void run() {
541                         try {
542                                 webOfTrustConnector.addContext(ownIdentity, context);
543                                 ownIdentity.addContext(context);
544                                 finish(true);
545                         } catch (PluginException pe1) {
546                                 logger.log(Level.WARNING, String.format("Could not add Context “%2$s” to Own Identity %1$s!", ownIdentity, context), pe1);
547                                 finish(false);
548                         }
549                 }
550
551         }
552
553         /**
554          * Job that removes a context from an {@link OwnIdentity}.
555          *
556          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
557          */
558         private class RemoveContextJob extends WebOfTrustContextUpdateJob {
559
560                 /**
561                  * Creates a new remove-context job.
562                  *
563                  * @param ownIdentity
564                  *            The own identity whose contexts to manage
565                  * @param context
566                  *            The context to remove
567                  */
568                 public RemoveContextJob(OwnIdentity ownIdentity, String context) {
569                         super(ownIdentity, context);
570                 }
571
572                 /**
573                  * {@inheritDoc}
574                  */
575                 @Override
576                 @SuppressWarnings("synthetic-access")
577                 public void run() {
578                         try {
579                                 webOfTrustConnector.removeContext(ownIdentity, context);
580                                 ownIdentity.removeContext(context);
581                                 finish(true);
582                         } catch (PluginException pe1) {
583                                 logger.log(Level.WARNING, String.format("Could not remove Context “%2$s” to Own Identity %1$s!", ownIdentity, context), pe1);
584                                 finish(false);
585                         }
586                 }
587
588         }
589
590         /**
591          * Base class for update jobs that deal with properties.
592          *
593          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
594          */
595         private class WebOfTrustPropertyUpdateJob extends WebOfTrustUpdateJob {
596
597                 /** The own identity to update properties on. */
598                 protected final OwnIdentity ownIdentity;
599
600                 /** The name of the property to update. */
601                 protected final String propertyName;
602
603                 /**
604                  * Creates a new property update job.
605                  *
606                  * @param ownIdentity
607                  *            The own identity to update the property on
608                  * @param propertyName
609                  *            The name of the property to update
610                  */
611                 @SuppressWarnings("synthetic-access")
612                 public WebOfTrustPropertyUpdateJob(OwnIdentity ownIdentity, String propertyName) {
613                         this.ownIdentity = ownIdentity;
614                         this.propertyName = propertyName;
615                 }
616
617                 //
618                 // OBJECT METHODS
619                 //
620
621                 /**
622                  * {@inheritDoc}
623                  */
624                 @Override
625                 public boolean equals(Object object) {
626                         if ((object == null) || !object.getClass().equals(getClass())) {
627                                 return false;
628                         }
629                         WebOfTrustPropertyUpdateJob updateJob = (WebOfTrustPropertyUpdateJob) object;
630                         return updateJob.ownIdentity.equals(ownIdentity) && updateJob.propertyName.equals(propertyName);
631                 }
632
633                 /**
634                  * {@inheritDoc}
635                  */
636                 @Override
637                 public int hashCode() {
638                         return getClass().hashCode() ^ ownIdentity.hashCode() ^ propertyName.hashCode();
639                 }
640
641                 /**
642                  * {@inheritDoc}
643                  */
644                 @Override
645                 public String toString() {
646                         return String.format("%s[ownIdentity=%s,propertyName=%s]", getClass().getSimpleName(), ownIdentity, propertyName);
647                 }
648
649         }
650
651         /**
652          * WebOfTrust update job that sets a property on an {@link OwnIdentity}.
653          *
654          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
655          */
656         private class SetPropertyJob extends WebOfTrustPropertyUpdateJob {
657
658                 /** The value of the property to set. */
659                 private final String propertyValue;
660
661                 /**
662                  * Creates a new set-property job.
663                  *
664                  * @param ownIdentity
665                  *            The own identity to set the property on
666                  * @param propertyName
667                  *            The name of the property to set
668                  * @param propertyValue
669                  *            The value of the property to set
670                  */
671                 public SetPropertyJob(OwnIdentity ownIdentity, String propertyName, String propertyValue) {
672                         super(ownIdentity, propertyName);
673                         this.propertyValue = propertyValue;
674                 }
675
676                 /**
677                  * {@inheritDoc}
678                  */
679                 @Override
680                 @SuppressWarnings("synthetic-access")
681                 public void run() {
682                         try {
683                                 if (propertyValue == null) {
684                                         webOfTrustConnector.removeProperty(ownIdentity, propertyName);
685                                         ownIdentity.removeProperty(propertyName);
686                                 } else {
687                                         webOfTrustConnector.setProperty(ownIdentity, propertyName, propertyValue);
688                                         ownIdentity.setProperty(propertyName, propertyValue);
689                                 }
690                                 finish(true);
691                         } catch (PluginException pe1) {
692                                 logger.log(Level.WARNING, String.format("Could not set Property “%2$s” to “%3$s” on Own Identity %1$s!", ownIdentity, propertyName, propertyValue), pe1);
693                                 finish(false);
694                         }
695                 }
696
697         }
698
699 }