1 /*
2 * Licensed under the Apache License, Version 2.0 (the "License");
3 * you may not use this file except in compliance with the License.
4 * You may obtain a copy of the License at
5 *
6 * http://www.apache.org/licenses/LICENSE-2.0
7 *
8 * Unless required by applicable law or agreed to in writing, software
9 * distributed under the License is distributed on an "AS IS" BASIS,
10 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 * See the License for the specific language governing permissions and
12 * limitations under the License.
13 *
14 */
15 package org.esigate.extension.http;
16
17 import org.apache.http.impl.conn.SystemDefaultDnsResolver;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
20
21 import java.net.InetAddress;
22 import java.net.UnknownHostException;
23 import java.util.Arrays;
24 import java.util.HashMap;
25 import java.util.Map;
26
27 /**
28 * DNS resolver that will resolve the host names against a collection held in-memory and fallback to an OS resolution
29 *
30 * @author Alexis Thaveau on 26/01/16.
31 */
32 public class CustomizableDNSResolver extends SystemDefaultDnsResolver {
33
34 /**
35 * Logger associated to this class.
36 */
37 private static final Logger LOG = LoggerFactory.getLogger(CustomizableDNSResolver.class);
38
39 /**
40 * In-memory collection that will hold the associations between a host name and an array of InetAddress instances.
41 */
42 private final Map<String, InetAddress[]> dnsMap = new HashMap<>();
43
44 /**
45 *
46 */
47 public CustomizableDNSResolver() {
48 }
49
50 /**
51 * Associates the given array of IP addresses to the given host in this DNS overrider. The IP addresses are assumed
52 * to be already resolved.
53 *
54 * @param host
55 * The host name to be associated with the given IP.
56 * @param ips
57 * array of IP addresses to be resolved by this DNS overrider to the given host name.
58 */
59 public void add(final String host, final InetAddress... ips) {
60 dnsMap.put(host, ips);
61 }
62
63 /**
64 * {@inheritDoc}
65 */
66 @Override
67 public InetAddress[] resolve(final String host) throws UnknownHostException {
68 InetAddress[] resolvedAddresses = dnsMap.get(host);
69 if (LOG.isInfoEnabled()) {
70 LOG.info("Resolving {} to {}", host, Arrays.deepToString(resolvedAddresses));
71 }
72 if (resolvedAddresses == null) {
73 resolvedAddresses = super.resolve(host);
74 }
75 return resolvedAddresses;
76 }
77
78 }