View Javadoc
1   /*
2    * Copyright 2018 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.resolver.dns;
17  
18  import io.netty.channel.EventLoop;
19  import io.netty.handler.codec.dns.DnsRecord;
20  
21  import java.net.InetAddress;
22  import java.net.InetSocketAddress;
23  import java.util.ArrayList;
24  import java.util.List;
25  
26  import static io.netty.util.internal.ObjectUtil.checkNotNull;
27  
28  /**
29   * {@link AuthoritativeDnsServerCache} implementation which delegates all operations to a wrapped {@link DnsCache}.
30   * This implementation is only present to preserve a upgrade story.
31   */
32  final class AuthoritativeDnsServerCacheAdapter implements AuthoritativeDnsServerCache {
33  
34      private static final DnsRecord[] EMPTY = new DnsRecord[0];
35      private final DnsCache cache;
36  
37      AuthoritativeDnsServerCacheAdapter(DnsCache cache) {
38          this.cache = checkNotNull(cache, "cache");
39      }
40  
41      @Override
42      public DnsServerAddressStream get(String hostname) {
43          List<? extends DnsCacheEntry> entries = cache.get(hostname, EMPTY);
44          if (entries == null || entries.isEmpty()) {
45              return null;
46          }
47          if (entries.get(0).cause() != null) {
48              return null;
49          }
50  
51          List<InetSocketAddress> addresses = new ArrayList<InetSocketAddress>(entries.size());
52  
53          int i = 0;
54          do {
55              InetAddress addr = entries.get(i).address();
56              addresses.add(new InetSocketAddress(addr, DefaultDnsServerAddressStreamProvider.DNS_PORT));
57          } while (++i < entries.size());
58          return new SequentialDnsServerAddressStream(addresses, 0);
59      }
60  
61      @Override
62      public void cache(String hostname, InetSocketAddress address, long originalTtl, EventLoop loop) {
63          // We only cache resolved addresses.
64          if (!address.isUnresolved()) {
65              cache.cache(hostname, EMPTY, address.getAddress(), originalTtl, loop);
66          }
67      }
68  
69      @Override
70      public void clear() {
71          cache.clear();
72      }
73  
74      @Override
75      public boolean clear(String hostname) {
76          return cache.clear(hostname);
77      }
78  }