1   
2   
3   
4   
5   
6   
7   
8   
9   
10  
11  
12  
13  
14  
15  
16  package io.netty.resolver.dns;
17  
18  import io.netty.channel.EventLoop;
19  import io.netty.util.AsciiString;
20  
21  import java.util.List;
22  
23  import static io.netty.util.internal.ObjectUtil.*;
24  
25  
26  
27  
28  public final class DefaultDnsCnameCache implements DnsCnameCache {
29      private final int minTtl;
30      private final int maxTtl;
31  
32      private final Cache<String> cache = new Cache<String>() {
33          @Override
34          protected boolean shouldReplaceAll(String entry) {
35              
36              return true;
37          }
38  
39          @Override
40          protected boolean equals(String entry, String otherEntry) {
41              return AsciiString.contentEqualsIgnoreCase(entry, otherEntry);
42          }
43      };
44  
45      
46  
47  
48      public DefaultDnsCnameCache() {
49          this(0, Cache.MAX_SUPPORTED_TTL_SECS);
50      }
51  
52      
53  
54  
55  
56  
57  
58      public DefaultDnsCnameCache(int minTtl, int maxTtl) {
59          this.minTtl = Math.min(Cache.MAX_SUPPORTED_TTL_SECS, checkPositiveOrZero(minTtl, "minTtl"));
60          this.maxTtl = Math.min(Cache.MAX_SUPPORTED_TTL_SECS, checkPositive(maxTtl, "maxTtl"));
61          if (minTtl > maxTtl) {
62              throw new IllegalArgumentException(
63                      "minTtl: " + minTtl + ", maxTtl: " + maxTtl + " (expected: 0 <= minTtl <= maxTtl)");
64          }
65      }
66  
67      @SuppressWarnings("unchecked")
68      @Override
69      public String get(String hostname) {
70          List<? extends String> cached =  cache.get(checkNotNull(hostname, "hostname"));
71          if (cached == null || cached.isEmpty()) {
72              return null;
73          }
74          
75          return cached.get(0);
76      }
77  
78      @Override
79      public void cache(String hostname, String cname, long originalTtl, EventLoop loop) {
80          checkNotNull(hostname, "hostname");
81          checkNotNull(cname, "cname");
82          checkNotNull(loop, "loop");
83          cache.cache(hostname, cname, Math.max(minTtl, (int) Math.min(maxTtl, originalTtl)), loop);
84      }
85  
86      @Override
87      public void clear() {
88          cache.clear();
89      }
90  
91      @Override
92      public boolean clear(String hostname) {
93          return cache.clear(checkNotNull(hostname, "hostname"));
94      }
95  
96      
97      int minTtl() {
98          return minTtl;
99      }
100 
101     
102     int maxTtl() {
103         return maxTtl;
104     }
105 }