View Javadoc

1   package com.bradmcevoy.http.http11.auth;
2   
3   import java.util.Date;
4   import java.util.Iterator;
5   import java.util.Map;
6   import java.util.UUID;
7   import java.util.concurrent.Executors;
8   import java.util.concurrent.ScheduledExecutorService;
9   import java.util.concurrent.ThreadFactory;
10  import org.slf4j.Logger;
11  import org.slf4j.LoggerFactory;
12  
13  import static java.util.concurrent.TimeUnit.*;
14  
15  /**
16   * Periodically checks a map of Nonce's to remove those which
17   * have expired.
18   *
19   * The map should be a reference to the live map in use by a NonceProvider
20   *
21   * @author brad
22   */
23  public class ExpiredNonceRemover implements Runnable {
24  
25      private static final Logger log = LoggerFactory.getLogger( ExpiredNonceRemover.class );
26  
27      private static final int INTERVAL = 10;
28  
29      private final Map<UUID, Nonce> nonces;
30      private final int nonceValiditySeconds;
31      private final ScheduledExecutorService scheduler;
32  
33      public ExpiredNonceRemover( Map<UUID, Nonce> nonces, int nonceValiditySeconds ) {
34          this.nonces = nonces;
35          this.nonceValiditySeconds = nonceValiditySeconds;
36          log.debug( "scheduling checks for expired nonces every " + INTERVAL + " seconds");
37          scheduler = Executors.newScheduledThreadPool( 1, new DaemonThreadFactory() );
38          scheduler.scheduleAtFixedRate( this, 10, INTERVAL, SECONDS );
39      }
40  
41      public void run() {
42          Iterator<UUID> it = nonces.keySet().iterator();
43          while( it.hasNext() ) {
44              UUID key = it.next();
45              Nonce n = nonces.get( key );
46              if( isExpired( n.getIssued())) {
47                  log.debug( "removing expired nonce: " + key);
48                  it.remove();
49              }
50          }
51      }
52  
53      private boolean isExpired( Date issued ) {
54          long dif = (System.currentTimeMillis() - issued.getTime()) / 1000;
55          return dif > nonceValiditySeconds;
56      }
57  
58      private class DaemonThreadFactory implements ThreadFactory {
59  
60          public Thread newThread( Runnable r ) {
61              Thread t = new Thread( r );
62              t.setDaemon( true );
63              return t;
64          }
65  
66      }
67  }