Prepare background updater to perform property and context updates, too.
[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 static 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 static class WebOfTrustUpdateJob {
165
166                 //
167                 // ACTIONS
168                 //
169
170                 /**
171                  * Performs the actual update operation.
172                  * <p>
173                  * The implementation of this class does nothing.
174                  */
175                 public void run() {
176                         /* does nothing. */
177                 }
178
179         }
180
181         /**
182          * Base class for WebOfTrust trust update jobs.
183          *
184          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
185          */
186         private static class WebOfTrustTrustUpdateJob extends WebOfTrustUpdateJob {
187
188                 /** The identity giving the trust. */
189                 protected final OwnIdentity truster;
190
191                 /** The identity receiving the trust. */
192                 protected final Identity trustee;
193
194                 /**
195                  * Creates a new trust update job.
196                  *
197                  * @param truster
198                  *            The identity giving the trust
199                  * @param trustee
200                  *            The identity receiving the trust
201                  */
202                 @SuppressWarnings("synthetic-access")
203                 public WebOfTrustTrustUpdateJob(OwnIdentity truster, Identity trustee) {
204                         super();
205                         this.truster = truster;
206                         this.trustee = trustee;
207                 }
208
209                 //
210                 // OBJECT METHODS
211                 //
212
213                 /**
214                  * {@inheritDoc}
215                  */
216                 @Override
217                 public boolean equals(Object object) {
218                         if ((object == null) || !object.getClass().equals(getClass())) {
219                                 return false;
220                         }
221                         WebOfTrustTrustUpdateJob updateJob = (WebOfTrustTrustUpdateJob) object;
222                         return ((truster == null) ? (updateJob.truster == null) : updateJob.truster.equals(truster)) && ((trustee == null) ? (updateJob.trustee == null) : updateJob.trustee.equals(trustee));
223                 }
224
225                 /**
226                  * {@inheritDoc}
227                  */
228                 @Override
229                 public int hashCode() {
230                         return getClass().hashCode() ^ ((truster == null) ? 0 : truster.hashCode()) ^ ((trustee == null) ? 0 : trustee.hashCode());
231                 }
232
233                 /**
234                  * {@inheritDoc}
235                  */
236                 @Override
237                 public String toString() {
238                         return String.format("%s[truster=%s,trustee=%s]", getClass().getSimpleName(), (truster == null) ? null : truster.getId(), (trustee == null) ? null : trustee.getId());
239                 }
240
241         }
242
243         /**
244          * Update job that sets the trust relation between two identities.
245          *
246          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
247          */
248         private class SetTrustJob extends WebOfTrustTrustUpdateJob {
249
250                 /** The score of the relation. */
251                 private final Integer score;
252
253                 /** The comment of the relation. */
254                 private final String comment;
255
256                 /**
257                  * Creates a new set trust job.
258                  *
259                  * @param truster
260                  *            The identity giving the trust
261                  * @param trustee
262                  *            The identity receiving the trust
263                  * @param score
264                  *            The score of the trust (from -100 to 100, may be
265                  *            {@code null} to remote the trust relation completely)
266                  * @param comment
267                  *            The comment of the trust relation
268                  */
269                 public SetTrustJob(OwnIdentity truster, Identity trustee, Integer score, String comment) {
270                         super(truster, trustee);
271                         this.score = score;
272                         this.comment = comment;
273                 }
274
275                 /**
276                  * {@inheritDoc}
277                  */
278                 @Override
279                 @SuppressWarnings("synthetic-access")
280                 public void run() {
281                         try {
282                                 if (score != null) {
283                                         if (trustee instanceof DefaultIdentity) {
284                                                 ((DefaultIdentity) trustee).setTrust(truster, new Trust(score, null, 0));
285                                         }
286                                         webOfTrustConnector.setTrust(truster, trustee, score, comment);
287                                 } else {
288                                         if (trustee instanceof DefaultIdentity) {
289                                                 ((DefaultIdentity) trustee).setTrust(truster, null);
290                                         }
291                                         webOfTrustConnector.removeTrust(truster, trustee);
292                                 }
293                         } catch (WebOfTrustException wote1) {
294                                 logger.log(Level.WARNING, "Could not set Trust value for " + truster + " -> " + trustee + " to " + score + " (" + comment + ")!", wote1);
295                         }
296                 }
297
298         }
299
300         /**
301          * Update job that retrieves the trust relation between two identities.
302          *
303          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
304          */
305         private class GetTrustJob extends WebOfTrustTrustUpdateJob {
306
307                 /**
308                  * Creates a new trust update job.
309                  *
310                  * @param truster
311                  *            The identity giving the trust
312                  * @param trustee
313                  *            The identity receiving the trust
314                  */
315                 public GetTrustJob(OwnIdentity truster, Identity trustee) {
316                         super(truster, trustee);
317                 }
318
319                 /**
320                  * {@inheritDoc}
321                  */
322                 @Override
323                 @SuppressWarnings("synthetic-access")
324                 public void run() {
325                         try {
326                                 Trust trust = webOfTrustConnector.getTrust(truster, trustee);
327                                 if (trustee instanceof DefaultIdentity) {
328                                         ((DefaultIdentity) trustee).setTrust(truster, trust);
329                                 }
330                         } catch (PluginException pe1) {
331                                 logger.log(Level.WARNING, "Could not get Trust value for " + truster + " -> " + trustee + "!", pe1);
332                         }
333                 }
334         }
335
336 }