• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

alibaba / java-dns-cache-manipulator / 1267

pending completion
1267

push

Appveyor

oldratlee
chore(ci): upgrade CI JDK 🤖

527 of 645 relevant lines covered (81.71%)

0.82 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

68.89
/library/src/main/java/com/alibaba/dcm/DnsCacheManipulator.java
1
package com.alibaba.dcm;
2

3
import com.alibaba.dcm.internal.InetAddressCacheUtilCommons;
4
import com.alibaba.dcm.internal.InetAddressCacheUtilForOld;
5
import com.alibaba.dcm.internal.InetAddressCacheUtilForNew;
6
import edu.umd.cs.findbugs.annotations.ReturnValuesAreNonnullByDefault;
7
import sun.net.InetAddressCachePolicy;
8

9
import javax.annotation.Nullable;
10
import javax.annotation.ParametersAreNonnullByDefault;
11
import java.io.InputStream;
12
import java.util.Arrays;
13
import java.util.List;
14
import java.util.Map;
15
import java.util.Properties;
16
import java.util.regex.Pattern;
17

18
import static com.alibaba.dcm.internal.InetAddressCacheUtilCommons.NEVER_EXPIRATION;
19
import static com.alibaba.dcm.internal.InetAddressCacheUtilCommons.isNewInetAddressImpl;
20

21

22
/**
23
 * DNS cache manipulator for querying/setting dns(in fact dns cache).
24
 * <p>
25
 * Throw {@link DnsCacheManipulatorException} if operation fail for all methods.
26
 *
27
 * @author Jerry Lee (oldratlee at gmail dot com)
28
 * @see DnsCache
29
 * @see DnsCacheEntry
30
 * @see DnsCacheManipulatorException
31
 */
32
@ParametersAreNonnullByDefault
33
@ReturnValuesAreNonnullByDefault
34
public final class DnsCacheManipulator {
35
    /**
36
     * Set a <b>never expired</b> dns cache entry.
37
     *
38
     * @param host host
39
     * @param ips  ips
40
     * @throws DnsCacheManipulatorException Operation fail
41
     * @see DnsCacheManipulator#setDnsCache(long, java.lang.String, java.lang.String...)
42
     */
43
    public static void setDnsCache(String host, String... ips) {
44
        try {
45
            if (isNewInetAddressImpl()) {
1✔
46
                InetAddressCacheUtilForNew.setInetAddressCache(host, ips, NEVER_EXPIRATION);
1✔
47
            } else {
48
                InetAddressCacheUtilForOld.setInetAddressCache(host, ips, NEVER_EXPIRATION);
1✔
49
            }
50
        } catch (Exception e) {
×
51
            final String message = String.format("Fail to setDnsCache for host %s ip %s, cause: %s",
×
52
                    host, Arrays.toString(ips), e);
×
53
            throw new DnsCacheManipulatorException(message, e);
×
54
        }
1✔
55
    }
1✔
56

57
    /**
58
     * Set a dns cache entry.
59
     *
60
     * @param expireMillis expire time in milliseconds.
61
     * @param host         host
62
     * @param ips          ips
63
     * @throws DnsCacheManipulatorException Operation fail
64
     */
65
    public static void setDnsCache(long expireMillis, String host, String... ips) {
66
        try {
67
            if (isNewInetAddressImpl()) {
1✔
68
                InetAddressCacheUtilForNew.setInetAddressCache(host, ips, expireMillis);
1✔
69
            } else {
70
                InetAddressCacheUtilForOld.setInetAddressCache(host, ips, expireMillis);
1✔
71
            }
72
        } catch (Exception e) {
×
73
            final String message = String.format("Fail to setDnsCache for host %s ip %s expireMillis %s, cause: %s",
×
74
                    host, Arrays.toString(ips), expireMillis, e);
×
75
            throw new DnsCacheManipulatorException(message, e);
×
76
        }
1✔
77
    }
1✔
78

79
    private static final Pattern COMMA_SEPARATOR = Pattern.compile("\\s*,\\s*");
1✔
80

81
    /**
82
     * Set dns cache entries by properties.
83
     *
84
     * @param properties input properties.<br>
85
     *                   e.g. {@code www.example.com=42.42.42.42}, <br>
86
     *                   or value is multiply ips seperated by {@code comma}
87
     *                   {@code www.example.com=42.42.42.42,43.43.43.43}
88
     * @throws DnsCacheManipulatorException Operation fail
89
     */
90
    public static void setDnsCache(Properties properties) {
91
        for (Map.Entry<Object, Object> entry : properties.entrySet()) {
1✔
92
            final String host = (String) entry.getKey();
1✔
93
            String ipList = (String) entry.getValue();
1✔
94

95
            ipList = ipList.trim();
1✔
96
            if (ipList.isEmpty()) continue;
1✔
97

98
            final String[] ips = COMMA_SEPARATOR.split(ipList);
1✔
99
            setDnsCache(host, ips);
1✔
100
        }
1✔
101
    }
1✔
102

103
    /**
104
     * Load dns config from properties file {@code dns-cache.properties} on classpath, then set to dns cache.
105
     * <p>
106
     * {@code dns-cache.properties} can be reset/customized by {@code JVM -D option} {@code dcm.config.filename}
107
     *
108
     * @throws DnsCacheManipulatorException Operation fail
109
     * @see DnsCacheManipulator#setDnsCache(java.util.Properties)
110
     * @see DnsCacheManipulator#loadDnsCacheConfig(java.lang.String)
111
     */
112
    public static void loadDnsCacheConfig() {
113
        final String DCM_CONFIG_FILE_NAME_KEY = "dcm.config.filename";
1✔
114
        final String dcmConfigFileName = System.getProperty(DCM_CONFIG_FILE_NAME_KEY, "dns-cache.properties");
1✔
115
        loadDnsCacheConfig(dcmConfigFileName);
1✔
116
    }
1✔
117

118
    /**
119
     * Load dns config from the specified properties file on classpath, then set dns cache.
120
     *
121
     * @param propertiesFileName specified properties file name on classpath.
122
     * @throws DnsCacheManipulatorException Operation fail
123
     * @see DnsCacheManipulator#setDnsCache(java.util.Properties)
124
     */
125
    public static void loadDnsCacheConfig(String propertiesFileName) {
126
        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(propertiesFileName);
1✔
127
        if (inputStream == null) {
1✔
128
            inputStream = DnsCacheManipulator.class.getClassLoader().getResourceAsStream(propertiesFileName);
1✔
129
        }
130
        if (inputStream == null) {
1✔
131
            throw new DnsCacheManipulatorException("Fail to find " + propertiesFileName + " on classpath!");
1✔
132
        }
133

134
        try {
135
            Properties properties = new Properties();
1✔
136
            properties.load(inputStream);
1✔
137
            inputStream.close();
1✔
138
            setDnsCache(properties);
1✔
139
        } catch (Exception e) {
×
140
            final String message = String.format("Fail to loadDnsCacheConfig from %s, cause: %s",
×
141
                    propertiesFileName, e);
142
            throw new DnsCacheManipulatorException(message, e);
×
143
        }
1✔
144
    }
1✔
145

146
    /**
147
     * Get a dns cache entry by {@code host}.
148
     *
149
     * @return dns cache. return {@code null} if no entry for host or dns cache is expired.
150
     * @throws DnsCacheManipulatorException Operation fail
151
     */
152
    @Nullable
153
    public static DnsCacheEntry getDnsCache(String host) {
154
        try {
155
            if (isNewInetAddressImpl()) {
1✔
156
                return InetAddressCacheUtilForNew.getInetAddressCache(host);
1✔
157
            } else {
158
                return InetAddressCacheUtilForOld.getInetAddressCache(host);
1✔
159
            }
160
        } catch (Exception e) {
×
161
            throw new DnsCacheManipulatorException("Fail to getDnsCache, cause: " + e, e);
×
162
        }
163
    }
164

165
    /**
166
     * Get whole dns cache info {@link DnsCache} including cache and negative cache.
167
     * <p>
168
     * If you only need cache without negative cache use convenient method {@link #listDnsCache()}.
169
     *
170
     * @return dns cache entries
171
     * @throws DnsCacheManipulatorException Operation fail
172
     * @see #listDnsCache()
173
     * @since 1.2.0
174
     */
175
    public static DnsCache getWholeDnsCache() {
176
        try {
177
            if (isNewInetAddressImpl()) {
1✔
178
                return InetAddressCacheUtilForNew.listInetAddressCache();
1✔
179
            } else {
180
                return InetAddressCacheUtilForOld.listInetAddressCache();
1✔
181
            }
182
        } catch (Exception e) {
×
183
            throw new DnsCacheManipulatorException("Fail to getWholeDnsCache, cause: " + e, e);
×
184
        }
185
    }
186

187
    /**
188
     * Get dns cache entries, without negative cache.
189
     * <p>
190
     * Same as {@code getWholeDnsCache().getCache()}
191
     *
192
     * @return dns cache entries
193
     * @throws DnsCacheManipulatorException Operation fail
194
     * @see #getWholeDnsCache()
195
     * @since 1.2.0
196
     */
197
    public static List<DnsCacheEntry> listDnsCache() {
198
        return getWholeDnsCache().getCache();
1✔
199
    }
200

201
    /**
202
     * Get dns cache entries, without negative cache.
203
     *
204
     * @return dns cache entries
205
     * @throws DnsCacheManipulatorException Operation fail
206
     * @deprecated this method name is confused: method name is "all" but without negative cache.
207
     * use {@link #listDnsCache} instead.
208
     */
209
    @Deprecated
210
    @SuppressWarnings("DeprecatedIsStillUsed")
211
    public static List<DnsCacheEntry> getAllDnsCache() {
212
        return listDnsCache();
1✔
213
    }
214

215
    /**
216
     * Get dns negative cache entries.
217
     * <p>
218
     * Same as {@code getWholeDnsCache().getNegativeCache()}
219
     *
220
     * @return dns negative cache entries
221
     * @throws DnsCacheManipulatorException Operation fail
222
     * @see #getWholeDnsCache()
223
     * @since 1.6.0
224
     */
225
    public static List<DnsCacheEntry> listDnsNegativeCache() {
226
        return getWholeDnsCache().getNegativeCache();
1✔
227
    }
228

229
    /**
230
     * Remove dns cache entry(including cache and negative cache), cause lookup dns server for host after.
231
     *
232
     * @param host host
233
     * @throws DnsCacheManipulatorException Operation fail
234
     * @see DnsCacheManipulator#clearDnsCache
235
     */
236
    public static void removeDnsCache(String host) {
237
        try {
238
            if (isNewInetAddressImpl()) {
1✔
239
                InetAddressCacheUtilForNew.removeInetAddressCache(host);
1✔
240
            } else {
241
                InetAddressCacheUtilForOld.removeInetAddressCache(host);
1✔
242
            }
243
        } catch (Exception e) {
×
244
            final String message = String.format("Fail to removeDnsCache for host %s, cause: %s", host, e);
×
245
            throw new DnsCacheManipulatorException(message, e);
×
246
        }
1✔
247
    }
1✔
248

249
    /**
250
     * Clear whole dns cache entries(including cache and negative cache), cause lookup dns server for all host after.
251
     *
252
     * @throws DnsCacheManipulatorException Operation fail
253
     */
254
    public static void clearDnsCache() {
255
        try {
256
            if (isNewInetAddressImpl()) {
1✔
257
                InetAddressCacheUtilForNew.clearInetAddressCache();
1✔
258
            } else {
259
                InetAddressCacheUtilForOld.clearInetAddressCache();
1✔
260
            }
261
        } catch (Exception e) {
×
262
            throw new DnsCacheManipulatorException("Fail to clearDnsCache, cause: " + e, e);
×
263
        }
1✔
264
    }
1✔
265

266
    /**
267
     * Get JVM DNS cache policy.
268
     *
269
     * @return cache seconds.
270
     * <ul>
271
     * <li> {@link InetAddressCachePolicy#FOREVER}({@code -1}) means never expired.(In effect, all negative value)</li>
272
     * <li> {@link InetAddressCachePolicy#NEVER}({@code 0}) never cached.</li>
273
     * </ul>
274
     * @throws DnsCacheManipulatorException Operation fail
275
     * @see InetAddressCachePolicy#get()
276
     * @see InetAddressCachePolicy#FOREVER
277
     * @see InetAddressCachePolicy#NEVER
278
     * @see InetAddressCachePolicy#DEFAULT_POSITIVE
279
     * @since 1.3.0
280
     */
281
    public static int getDnsCachePolicy() {
282
        try {
283
            return InetAddressCacheUtilCommons.getDnsCachePolicy();
1✔
284
        } catch (Exception e) {
×
285
            throw new DnsCacheManipulatorException("Fail to getDnsCachePolicy, cause: " + e, e);
×
286
        }
287
    }
288

289
    /**
290
     * Set JVM DNS cache policy.
291
     * <p>
292
     * NOTE: if Security Manage is turn on, JVM DNS cache policy set will not take effective. You can check by method {@link #getDnsCachePolicy()}.
293
     *
294
     * @param cacheSeconds set default dns cache time. Special input case:
295
     *                     <ul>
296
     *                     <li> {@link InetAddressCachePolicy#FOREVER}({@code -1}) means never expired.(In effect, all negative value)</li>
297
     *                     <li> {@link InetAddressCachePolicy#NEVER}({@code 0}) never cached.</li>
298
     *                     </ul>
299
     * @throws DnsCacheManipulatorException Operation fail
300
     * @see InetAddressCachePolicy
301
     * @see InetAddressCachePolicy#cachePolicy
302
     * @see InetAddressCachePolicy#get()
303
     * @see InetAddressCachePolicy#FOREVER
304
     * @see InetAddressCachePolicy#NEVER
305
     * @see InetAddressCachePolicy#DEFAULT_POSITIVE
306
     * @since 1.3.0
307
     */
308
    public static void setDnsCachePolicy(int cacheSeconds) {
309
        try {
310
            InetAddressCacheUtilCommons.setDnsCachePolicy(cacheSeconds);
1✔
311
        } catch (Exception e) {
×
312
            throw new DnsCacheManipulatorException("Fail to setDnsCachePolicy, cause: " + e, e);
×
313
        }
1✔
314
    }
1✔
315

316
    /**
317
     * JVM DNS negative cache policy.
318
     *
319
     * @return negative cache seconds.
320
     * <ul>
321
     * <li> {@link InetAddressCachePolicy#FOREVER}({@code -1}) means never expired.(In effect, all negative value)</li>
322
     * <li> {@link InetAddressCachePolicy#NEVER}({@code 0}) never cached.</li>
323
     * </ul>
324
     * @throws DnsCacheManipulatorException Operation fail
325
     * @see InetAddressCachePolicy#getNegative()
326
     * @see InetAddressCachePolicy#FOREVER
327
     * @see InetAddressCachePolicy#NEVER
328
     * @since 1.3.0
329
     */
330
    public static int getDnsNegativeCachePolicy() {
331
        try {
332
            return InetAddressCacheUtilCommons.getDnsNegativeCachePolicy();
1✔
333
        } catch (Exception e) {
×
334
            throw new DnsCacheManipulatorException("Fail to getDnsNegativeCachePolicy, cause: " + e, e);
×
335
        }
336
    }
337

338
    /**
339
     * Set JVM DNS negative cache policy.
340
     *
341
     * @param negativeCacheSeconds set default dns cache time. Special input case:
342
     *                             <ul>
343
     *                             <li> {@link InetAddressCachePolicy#FOREVER}({@code -1}) means never expired.(In effect, all negative value)</li>
344
     *                             <li> {@link InetAddressCachePolicy#NEVER}({@code 0}) never cached.</li>
345
     *                             </ul>
346
     * @throws DnsCacheManipulatorException Operation fail
347
     * @see InetAddressCachePolicy
348
     * @see InetAddressCachePolicy#FOREVER
349
     * @see InetAddressCachePolicy#NEVER
350
     * @since 1.3.0
351
     */
352
    public static void setDnsNegativeCachePolicy(int negativeCacheSeconds) {
353
        try {
354
            InetAddressCacheUtilCommons.setDnsNegativeCachePolicy(negativeCacheSeconds);
1✔
355
        } catch (Exception e) {
×
356
            throw new DnsCacheManipulatorException("Fail to setDnsNegativeCachePolicy, cause: " + e, e);
×
357
        }
1✔
358
    }
1✔
359

360
    private DnsCacheManipulator() {
361
    }
362
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc