1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 package org.apache.hc.client5.http.impl;
28
29 import java.net.InetAddress;
30 import java.net.UnknownHostException;
31 import java.util.Arrays;
32 import java.util.Map;
33 import java.util.concurrent.ConcurrentHashMap;
34
35 import org.apache.hc.client5.http.DnsResolver;
36 import org.apache.hc.core5.annotation.Contract;
37 import org.apache.hc.core5.annotation.ThreadingBehavior;
38 import org.apache.hc.core5.util.Args;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42
43
44
45
46
47 @Contract(threading = ThreadingBehavior.STATELESS)
48 public class InMemoryDnsResolver implements DnsResolver {
49
50
51 private static final Logger LOG = LoggerFactory.getLogger(InMemoryDnsResolver.class);
52
53
54
55
56
57 private final Map<String, InetAddress[]> dnsMap;
58
59
60
61
62
63 public InMemoryDnsResolver() {
64 dnsMap = new ConcurrentHashMap<>();
65 }
66
67
68
69
70
71
72
73
74
75
76
77 public void add(final String host, final InetAddress... ips) {
78 Args.notNull(host, "Host name");
79 Args.notNull(ips, "Array of IP addresses");
80 dnsMap.put(host, ips);
81 }
82
83
84
85
86 @Override
87 public InetAddress[] resolve(final String host) throws UnknownHostException {
88 final InetAddress[] resolvedAddresses = dnsMap.get(host);
89 if (LOG.isInfoEnabled()) {
90 LOG.info("Resolving {} to {}", host, Arrays.deepToString(resolvedAddresses));
91 }
92 if(resolvedAddresses == null){
93 throw new UnknownHostException(host);
94 }
95 return resolvedAddresses;
96 }
97
98 @Override
99 public String resolveCanonicalHostname(final String host) throws UnknownHostException {
100 final InetAddress[] resolvedAddresses = resolve(host);
101 if (resolvedAddresses.length > 0) {
102 return resolvedAddresses[0].getCanonicalHostName();
103 }
104 return host;
105 }
106 }